How to add `style=display:"block"` to an element using jQuery?

JavascriptJqueryHtmlCss

Javascript Problem Overview


How to add style=display:"block" to an element in jQuery?

Javascript Solutions


Solution 1 - Javascript

$("#YourElementID").css("display","block");

Edit: or as dave thieben points out in his comment below, you can do this as well:

$("#YourElementID").css({ display: "block" });

Solution 2 - Javascript

There are multiple function to do this work that wrote in bottom based on priority.

Set one or more CSS properties for the set of matched elements.

$("div").css("display", "block")

// Or add multiple CSS properties
$("div").css({
  display: "block",
  color: "red",
  ...
})


Display the matched elements and is roughly equivalent to calling .css("display", "block")

You can display element using .show() instead

$("div").show()


Set one or more attributes for the set of matched elements.

If target element hasn't style attribute, you can use this method to add inline style to element.

$("div").attr("style", "display:block")

// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")


  • JavaScript

You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.

var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red"; 
// Multiple properties
div.setAttribute("style", "display:block; color:red");

Solution 3 - Javascript

Depending on the purpose of setting the display property, you might want to take a look at

$("#yourElementID").show()

and

$("#yourElementID").hide()

Solution 4 - Javascript

If you need to add multiple then you can do it like this:

$('#element').css({
    'margin-left': '5px',
    'margin-bottom': '-4px',
    //... and so on
});

As a good practice I would also put the property name between quotes to allow the dash since most styles have a dash in them. If it was 'display', then quotes are optional but if you have a dash, it will not work without the quotes. Anyways, to make it simple: always enclose them in quotes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSomeoneView Question on Stackoverflow
Solution 1 - JavascriptColin BrockView Answer on Stackoverflow
Solution 2 - JavascriptMohammadView Answer on Stackoverflow
Solution 3 - JavascriptDesign by AdrianView Answer on Stackoverflow
Solution 4 - JavascriptCodingYoshiView Answer on Stackoverflow