简体   繁体   中英

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.

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

试试这个,让我知道它是否有帮助

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

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();)})

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);
}
$("#items .item").each(function(index,element){
    var labelText = $('label', element).text(); // or .html()
    console.log(labelText);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM