Get first child node of specific type - JavaScript

JavascriptDom

Javascript Problem Overview


Is it possible to get a child dom element, which will be the first child of a specific type.

For example in both of these examples I want to get the img element:

<a id="mylink" href="#"><img src="myimage.jpg" /></a>

vs.

<a id="mylink" href="#"><span></span><img src="myimage.jpg" /></a>

Javascript Solutions


Solution 1 - Javascript

Try this

var firstIMG = document.getElementById('mylink').getElementsByTagName('img')[0];

Solution 2 - Javascript

You can also use querySelector:

var firstImg = document.querySelector("#mylink > img:first-of-type");

Solution 3 - Javascript

var anchor = document.getElementById('mylink');
var images = anchor.getElementsByTagName('img');
var image = images.length ? images[0] : null;

Solution 4 - Javascript

Here is a javascript function

function getFirst(con,tag)
{
    return con.getElementsByTagName(tag)[0];
}


//html markup
<a id="mylink" href="#"><img src="myimage.jpg" /></a>
<a id="mylink1" href="#"><img src="myimage.jpg" /></a>

//test
var con=document.getElementById('mylink');
var first=getFirst(con,'img');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1559590View Question on Stackoverflow
Solution 1 - JavascriptyogiView Answer on Stackoverflow
Solution 2 - JavascriptZetaView Answer on Stackoverflow
Solution 3 - JavascriptMichael RobinsonView Answer on Stackoverflow
Solution 4 - Javascriptspaceman12View Answer on Stackoverflow