1

Let's say I have a class ".someClass":

.someClass {
    display: none;
}

Then in javascript code the div is created and then the class is applied for the div:

var myDiv = document.createElement("div");
myDiv.className = "someClass";

Is it possible now to check if "myDiv" has the style "display: none" or not without appending it to the web page?

Or is the only way to test the "display" property is to append "myDiv" to the page, then quickly check "$(myDiv).css('display')" and then remove it from page?

Thank you, really appreciate help.

Brahma Dev
  • 1,955
  • 1
  • 12
  • 18
Aremyst
  • 1,480
  • 2
  • 19
  • 33
  • Shouldn't it be `myDiv.className="someClass";`? – rt2800 Mar 20 '14 at 12:09
  • Try the answer from this post. Hope it works for you. [Get a CSS value from external style sheet with Javascript/jQuery][1] [1]: http://stackoverflow.com/questions/2707790/get-a-css-value-from-external-style-sheet-with-javascript-jquery – Umair Hafeez Mar 20 '14 at 12:21

5 Answers5

3

You can't check for that property until you add the element to the page. CSS rules belong to he document, and are, in many cases, dependent on where in the DOM tree the element is. Until the element is added, CSS properties are not filled.

You can test it in the chrome console:

var div = document.createElement('div');
getComputedStyle(div);

You'll get an object with all CSS properties applied to the DIV, and you'll see that they are all empty.

Now, if you do:

document.body.appendChild(div);
getComputedStyle(div);

You'll see that they are now filled. This also happens when an element is removed from the DOM, not just when it hasn't been appended.

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
1

Each element, that is not appended to any DOM element, is considered not visible.

Btw, I'd suggest you to use the following line code to verify if an element is hidden or not.

jQuery(element).is(':visible')
MrDevel
  • 166
  • 2
  • 13
1

You'll need to create the div. However to prevent any hiccups for the user, try creating a temporary element positioned absolute in the negative index. i.e. left:-9999px top -9999px also preferably opacity 0; just in case the 'someClass' element is also positioned absolute..

Then create/insert the required 'someClass' element in the above element.

Brahma Dev
  • 1,955
  • 1
  • 12
  • 18
0

See the fiddle: http://jsfiddle.net/9SDu5/

var myDiv = document.createElement("div");
myDiv.className = "someClass";
$(myDiv).hide().appendTo("body");
alert($(myDiv).css("display"));
$(myDiv).remove();
Umair Hafeez
  • 407
  • 2
  • 9
0
var myDiv = document.createElement("div");
myDiv.className = "someClass";
if ($(".someClass").is(":visible") == false) { console.log("yes");}

will result in yes till you even if

myDiv.style.display="block";

so I think adding it to dom is important

Aameer
  • 1,366
  • 1
  • 11
  • 30