1

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

2 Answers 2

4

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);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.