How to hide elements that were dynamically created in jquery?
I'm trying to hide some divs that I have created dynamically using the .hide() funct开发者_开发知识库ion but no luck. I think the reason it's not working is because elements that have not yet been added to the DOM. Is there a way around it?
$('<div class="toggle_container"></div>').html('<div
class="block"><p>'+title+'</p></div>').appendTo('#page-wrap'); //dynamic creation of divs
$(".toggle_container").hide(); //trying to hide,but not working
Thanks
You can always use
document.getElementById('id').style.display = "none";
As this will look at all current DOM elements.
Is page-wrap
already in the DOM when you do this? Because if so, it seems to work: http://jsbin.com/ukite3 I've tried it with Chrome and Firefox on Linux, and IE8 and IE6 on Windows. That example uses your code above, then shows the div two seconds later (to prove that the addition worked). Works fine. If I comment out the part doing the hiding, I see the new content immediately.
If page-wrap
isn't already in the DOM, you can't use selectors like $(".toggle_container")
to update them, because selectors look through the DOM tree. (Your appendTo
call should fail as well, since it will look in the DOM tree for an element with that ID.) If page-wrap
isn't already in the DOM, you'd want to change your code like so:
var pageWrap = /* ...whatever creates the page-wrap element ... */;
var toggle = $('<div class="toggle_container"></div>');
toggle.html('<div class="block"><p>'+title+'</p></div>');
toggle.appendTo(pageWrap);
toggle.hide();
(You can condense that a little bit if you want to, chaining the last three lines.) Live example: http://jsbin.com/ukite3/2
Off-topic: I find that in situations like this, creating a self-contained, minimalist example can really help me find the actual underlying problem. I can't count the number of times I've been sure something was X, then isolated X out and found that no, it was Y all along... :-)
It works fine http://jsfiddle.net/TMtCz/ You could however hide it before you append it, like so:
$('<div class="toggle_container"></div>').hide().html('<div class="block"><p>'+title+'</p></div>').appendTo('#page-wrap');
Use .live(), but as far as I know you have to use an event to do the actual hiding. When does the div have to be hidden?
Anyway, live()
makes sure that elements that are created in the future are also included in a certain bind, whereas regular binds only work on elements that are in the DOM at the time of pageload.
$(".toggle_container").live('click', function() {
$(this).hide();
});
Binds a click-event to the container as soon as it 'lives'. See here for reference.
精彩评论