Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search the children of a HTMLDivElement?

Tags:

javascript

dom

I have an HTMLDivElement, and my goal is to find a div nested beneath this.

Ideally I'd want something like getElementById, but that function doesn't work for HTMLDivElement.

Do I need to manually traverse the graph, or is there an easier way?

like image 253
A Question Asker Avatar asked Jan 11 '12 20:01

A Question Asker


People also ask

How do you get all children of an element?

To get all child nodes of an element, you can use the childNodes property. This property returns a collection of a node's child nodes, as a NodeList object. By default, the nodes in the collection are sorted by their appearance in the source code. You can use a numerical index (start from 0) to access individual nodes.

What is a child element?

A child element will be included in a UC award where a claimant is responsible for a child or qualifying young person who normally lives with them. Where a child lives in 2 separate households, claimants will be expected to agree who has main responsibility and claim accordingly.


2 Answers

Demo: http://jsfiddle.net/ThinkingStiff/y9K9Y/

If the <div> you're searching for has a class, you can use getElementsByClassName():

document.getElementById( 'parentDiv' ).getElementsByClassName( 'childDiv' )[0]; 

If it doesn't have a class you can use getElementsByTagName():

document.getElementById( 'parentDiv' ).getElementsByTagName( 'div' )[0]; 

And if it has an id you can, of course, just use getElementById() to find it no matter where it is in the DOM:

document.getElementById( 'childDiv' ); 
like image 198
ThinkingStiff Avatar answered Sep 23 '22 05:09

ThinkingStiff


  //For immediate children     var children = document.getElementById('id').childNodes;     //or for all descendants     var children = document.getElementById('id').getElementsByTagName('*'); 
like image 44
Emmanuel N Avatar answered Sep 21 '22 05:09

Emmanuel N