In the following code:
$(document).ready( function () {
var hideInit = function () {
$(selector1).hide();
}
var loadInit = function () {
//get data
var thingo = $('<div />');
//populate thingo with a bunch of divs matching selector1
$(selector2).append(thingo);
}
loadInit();
hideInit();
});
I am parsing some data and populating the DOM with it in loadInit, and then I wish to .hide each of the elements present in the DOM that was just created which match selector1.
Unfortunately the elements are not being hidden – what have I done wrong here?
Thanks!
Solution
My selectors weren’t incorrect, as suggested by many, but it was the order in which I was calling the functions. In order to guarantee that hideInit runs after loadInit has complete, I call it at the end, inside, of loadInit.
$(document).ready( function () {
var hideInit = function () {
$(selector1).hide();
}
var loadInit = function () {
//get data
var thingo = $('<div />');
//populate thingo with a bunch of divs matching selector1
$(selector2).append(thingo);
hideInit();
}
loadInit();
});
Thanks for your comments/ answers!
NOT related to : Using jQUery hide() on newly created dom elements
This can be achieved with a single line that manipulates the DOM using the
append,filterandhidejQuery methods.$('selector2').append(thingo)– append the items.filter('selector1')– of the original selector, only select those matching the filter.hide()– hide the filtered itemsLike this:
Optionally, if you want to hide the appended items, you’ll want to add an additional chain after the
filter, whereby you could use thefind()method, like this: