Jan Kowalski
Jan Kowalski

Reputation: 293

Jquery select DOM elements and access inner elements

I'm trying to make small script. I have main div that has 300 inner divs and I access them by:

$("#items").find(".item").each(function(index,ele){
    console.log(ele);
})

So it logs me all the inner divs. Now i want to access labels and read their inner html of these found divs.

How i can do that? Tried to mess with ele.label & ele.$("label"), but it doesn't work.

Upvotes: 3

Views: 906

Answers (5)

Onur Kucukkece
Onur Kucukkece

Reputation: 1758

$("#items .item").each(function(index,element){
    var labelText = $('label', element).text(); // or .html()
    console.log(labelText);
})

Upvotes: 0

orangespark
orangespark

Reputation: 649

How about pure javascript :)

itemslabelArr = document.querySelectorAll("#items .item label")
for (var i = 0, len = itemslabelArr.length; i < len; i++) {
console.log(itemslabelArr[i].innerHTML);
}

Upvotes: 0

Akshay Vijay Jain
Akshay Vijay Jain

Reputation: 15945

Try this and let me know if it helps

$("#items").find(".item").each((i, e) => console.log(e.innerHTML))

Upvotes: 0

pavel
pavel

Reputation: 27092

You need to use .find or .children to find children/nested elements.

$(ele).children('label') // takes just direct children
$(ele).find('label') // take all nested labels

Upvotes: 2

freelancer
freelancer

Reputation: 1164

Either you can do it directly with html() method to get innerHTML of label.

$("#items").find(".item label").each(function(index,ele){
    console.log($(ele).html())});

Or after loop

$("#items").find(".item").each(function(index,ele){
    console.log($(ele).find('label').html();)})

Upvotes: 0

Related Questions