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


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

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


Solution 1:


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

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

Solution 2:

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




Solution 3:

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
  display: "block",
  color: "red",

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

You can display element using .show() instead


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 = "block";
// Multiple properties = "display:block; color:red"; 
// Multiple properties
div.setAttribute("style", "display:block; color:red");

Solution 4:

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

    '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.