简体   繁体   中英

Adding different list items to array of unordered lists

I have three unordered lists that have the same class. I loop through them and I'm trying to add items that match certain descriptions to each of them, but when I try to reference the list by its index, it says it can't find the append function. The code looks something like this:

demoTypes.upcomingDemos.map(function(item) {
    var itemElement = "<li>My Item</li>";
    if (demoTypes.type == "Basic") {
        $(".unorderedListSection")[0].append(itemElement);
    } else if (demoTypes.type == "Intermediate") {
        $(".unorderedListSection")[1].append(itemElement);
    } else if (demoTypes.type == "Advanced") {
        $(".unorderedListSection")[2].append(itemElement);
    }

});

Adding the items to ALL the lists seems to work fine for some reason (although I obviously don't want to do this):

$(".unorderedListSection").append(itemElement);

When accessing a jQuery object by index it returns a DOMElement, not a jQuery object, hence you get the error about the lack of an append() method.

To fix this, use the eq() method:

demoTypes.upcomingDemos.map(function(item) {
    var itemElement = "<li>My Item</li>";
    if (demoTypes.type == "Basic") {
        $(".unorderedListSection").eq(0).append(itemElement);
    } else if (demoTypes.type == "Intermediate") {
        $(".unorderedListSection").eq(1).append(itemElement);
    } else if (demoTypes.type == "Advanced") {
        $(".unorderedListSection").eq(2).append(itemElement);
    }
});

The jQuery function returns an object which is a wrapper around an array of elements. When you access an item at a given index ( $(selector)[index] ) you no longer have a jQuery object but a raw element.

 console.log($('p').html()); console.log($('p')[0].toString()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>A</p> <p>B</p> <p>C</p> 

Instead, you can use the eq method to get an element at an index wrapped in a jQuery object.

 console.log($('p').eq(0).html()); console.log($('p').eq(1).html()); console.log($('p').eq(2).html()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>A</p> <p>B</p> <p>C</p> 

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