pedroyanky pedroyanky - 4 months ago 9
jQuery Question

Attempting to get the image property via jquery traversal but am getting undefined

I am trying to traverse the DOM with jQuery, but I am getting

undefined
. This is the code:



alert($('#para1').childNodes[1].nodeName);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="para1">
<img src=........>
</p>





What is the proper way to do this?

Answer

There are so many ways to get the img element and the attributes ...

$('#para1 img').attr("src");
// or
$('img', $('#para1')).attr("src");
// or
$('#para1').find("img").attr("src");
// or
$('#para1').children("img").attr("src");
/// ...

If you want the tag name, replace .attr("src") with .prop("tagName").

$('#para1').children().each(function() {
    alert($(this).prop("tagName"));
});

To loop child elements by an index there are even many, many ways to do this. Just some possible ways:

// using the index with :eq()
var tag = $("#para1 *").eq(0).prop("tagName");

// another way using :eq()
var tag = $("#para1").children().eq(1).prop("tagName");

// another way using :eq()
var tag = $("#para1 :eq(2)").prop("tagName");

// using DOM elements out of jQuery
var tag = $("#para1").children().get(0).tagName;

// another way using DOM elements out of jQuery
var tag = $("#para1").children()[1].tagName;

// another way using DOM elements out of jQuery
var tag = $("#para1 *")[2].tagName;

// create a arra map out of all children
var tags = $("#para1").children().map(function() {
    return $(this).prop("tagName");
}).get();

Working example.