Whenever I attempt that using either Chrome or Safari (both WebKit-based browsers), upon inspecting the element with the provided tools, it does not show any style.display
property at all. Hence, the default div
style of display: block
is used. (Here's an updated version with text inside the div for better visibility and inspection with DOM inspector.)
Therefore, my suspicion points to another issue. Is there a possibility of intervening code causing a failure on WebKit, leading to d.show();
never actually being called? This scenario could potentially explain the situation. It is an easy task utilizing the integrated tools in Chrome or Safari to set a breakpoint on the code generating the div and go through it step by step.
In response to your query:
...how can i check if an element has not been inserted into the DOM yet?
This question was recently raised here on StackOverflow, and one of the jQuery-specific answers offered was quite clever:
if (d.closest("body").length == 0) {
// The element is not yet within the DOM
}
Update: Regarding your previous comment
Examine this test page using Firefox. In Firefox, the div explicitly defines "style=display: block;." Under Webkit, it has an empty style attribute. I am utilizing the built-in inspectors in both Firefox and Safari.
I understand now. The issue does not involve a display: none
problem in WebKit browsers (your mention of it in the question led me astray), but rather Firefox (and possibly other Gecko browsers) displaying display: block
on the element instead.
In handling this situation, I would suggest the following approach:
var d = $("<div class='test'></div>");
d.addClass("hidden");
$("body").prepend(d);
d.removeClass("hidden");
...accompanied by this CSS:
.hidden {
display: none;
}
View live demonstration
This method guarantees avoidance of setting a style.display
property altogether.
Update 2: Another option is directly removing the style.display
property:
var d = $("<div class='test'>Hi there</div>");
d.hide();
$("body").prepend(d);
d.show();
d[0].style.display = "";
See live example
If you are considering effects such as fadeIn
, utilize the callback function:
var d = $("<div class='test'>Hi there</div>");
d.hide();
$("body").prepend(d);
d.fadeIn(function() {
this.style.display = "";
});
Explore live demo