简体   繁体   中英

Get Child inner HTML

So guys, I have some HTML like this:

<ul id="view-id54795_breadcrumbs" class="xbreadcrumbs">
    <li id="view-id54795_bcitem0" class="ncurrent">All XYZ</li>
    <li id="view-id54795_bcitem1" class="current">ABC</li>
</ul> 

I need the text in the children, so I started with simple functions like:

console.log($('#'+t.view.id+'_breadcrumbs').childNodes);
//console.log($('#'+t.view.id+'_breadcrumbs').getChildren());

Both of which didnt work. I also tried the function below

$(function(){
    var child = $('#'+t.view.id+'_breadcrumbs').find('li.t.view.id_');
    console.log(child.innerHTML);
    var idArray = new Array();

    if(child.length) {                              
        $.each(child,function(i,entry) {                                
            idArray.push($(this).attr('id'));
        });
    }

    console.log(idArray);                               
});

PS.

The function code above has been taken from the reference post using jquery .find() to get children . Any suggestions would be highly appreciated.

Thank you.

What about this selector instead?

$('.xbreadcrumbs li')

A more complete version would be:

$(function(){ 
    var children = $('.xbreadcrumbs li');
    children.each(function(i,v)
    {
       console.log($(v).text()); 
     });                         
});
var list = document.getElementById('view-id54795_breadcrumbs');
list.forEach(function(element) {
console.log(element.innerHTML);
});

note: forEach is only available in ECMAScript 5 implemtation, sorry for vanilla JS, i don't know jQuery

Try something like this:

var ul = $('#'+t.view.id+'_breadcrumbs');
var children = ul.find('li[id^="' + t.view.id + '"]');

var childText = [];

for(var i = 0; i < children.length; i++){
    childText.push(children[i].innerHTML);
}

The jQuery find uses the 'startsWith' selector, so any li whose id begins with t.view.id will be returned.

The childText should be filled with each li text.

See the fiddle

Just select your ul and do a .find() passing the li tag selector

$(function(){
var children = $('#view-id54795_breadcrumbs').find('li');

var idArray = new Array();

if(children.length) {                              
    $.each(child,function(i,entry) {    

        console.log($(this).html());

        idArray.push($(this).attr('id'));
    });
}

console.log(idArray);                               

});

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