To give a brief high-level, I have a search results page with custom nifty boxes for each result. I take a cloneNode(true) of the search results and store it in a jQuery object. I then want to affect the contents of its children by targeting by ID.
Assuming I have an HTML structure such as this:
<div id="parent">
<div id="child-1">
</div>
<div id="child-2">
</div>
</div>
And I take a clone of parent like so:
var templatePage = $('div#parent')[0].cloneNode(true);
Now I want to affect the CSS of #child-2
with something similar to:
templatePage.jQueryGetElementById('child-2').css("display", "none");
I can't use $('#child-2').css("display", "none");
because I need the div that is in the variable, not the page.
Surely there's just some little thing I'm missing but alas, Google is not being kind to me on this one.
jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.
Select the parent element whose child element is going to be selected. Use . querySelector() method on parent. Use the className of the child to select that particular child.
jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.
$("#child-1", templatePage).css("display", "none");
You can see an example of this here. This works by passing a context (templatePage
) to jQuery, and as templatePage
contains a DOM element, #child-1
is looked for within that DOM element, rather than the document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With