Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to select elements inside a selected node element?

Status
Not open for further replies.

studio66

Technical User
Jan 22, 2011
3
CA
How can I select the SPAN elements inside of a HTML code that has a pattern/structure as follows:

<div id="main-container">

<img src="pic1.jpg"
<span>some text</span>

<img src="pic2.jpg"
<span>other text</span>

</div>
 
Perhaps something like this:
Code:
        var MCdiv=document.getElementById('main-container');
	var spans=new Array();
	var i=0;
	for(var x in MCdiv.childNodes){
	    if(MCdiv.childNodes[x].tagName=="SPAN"){
	   	   spans[i]=MCdiv.childNodes[x];
	   i++;
	  }
	}

The spans array will contain object references to all spans inside the div.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
And if we add a link to each segment as follows? Does it makes any difference if there are other elements between "main-container" and the SPAN as far as they are still under the "main-container" DIV?

<div id="main-container">

<a href="#">
<img src="pic1.jpg"
<span>some text</span>
</a>

<a href="#">
<img src="pic2.jpg"
<span>other text</span>
</a>

</div>
 
Nope, as the code above will look for spans specifically. If there is anything else there it will just ignore it.

Of course if there are no spans, the spans array will be empty.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Hi

studio66, what are you looking for, children or descendants ?
For descendants the [tt]getElementsByTagName()[/tt] method would be better :
Code:
[b]var[/b] MCdiv[teal]=[/teal]document[teal].[/teal][COLOR=darkgoldenrod]getElementById[/color][teal]([/teal][green][i]'main-container'[/i][/green][teal]);[/teal]
[b]var[/b] spans[teal]=[/teal]MCdiv[teal].[/teal][COLOR=darkgoldenrod]getElementsByTagName[/color][teal]([/teal][green][i]'span'[/i][/green][teal]);[/teal]

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top