Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the child of a jQuery object stored in a variable

Tags:

jquery

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.

like image 276
Inversus Avatar asked Jul 13 '11 20:07

Inversus


People also ask

How do you get children of children in jQuery?

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.

How do you get the children of the $( this selector?

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.

How do I select a specific child in Javascript?

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.

Can we get the children element from the parent element using jQuery?

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.


1 Answers

$("#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.

like image 137
James Allardice Avatar answered Nov 15 '22 05:11

James Allardice