javascriptjqueryhtmlhtml-liststargeting

Attempting to target a particular number LI item in an unordered list and append html


Greetings stackoverflow,

Ive got html code saved as a js variable named 'test'.

I then am attempting to target a specific (the 5th) li item and append the HTML in a line under that with :

var target = $("ul[class='productWrapper']>li:nth-child(5)");

$(test).insertAfter($(target));

I believe I have a syntax issue with how i am trying to target that LI element and im not sure if insertAfter is the proper method to use for this task.

All of your thoughts are welcome!


Solution

  • I think whatever you have there is about right, @JoeG. I've taken the liberty of putting a bit more context around it and it seems to work just fine. I changed your syntax a tiny bit, but not the main line in question. There are two elements only to make it clear that the .insertAfter() is hitting the right one, and only that one.

    Here's the HTMl with script at the bottom.

    <html dir="ltr" lang="en-US">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
        <style>
            body { display: flex; flex-direction: column; }
            ul { display: inline-block; list-style-type: none; text-align: left; background: #ccc; border-radius: 1rem; padding: 1rem; margin: 2rem auto; }
            .inserted { color: green;}
        </style>
    </head>
    <body>
        <ul class="productWrapper">
            <li>First</li>
            <li>Second</li>
            <li>Third</li>
            <li>Fourth</li>
            <li>Fifth</li>
            <li>Sixth</li>
        </ul>
        <ul class="someOtherClass">
            <li>Other First</li>
            <li>Other Second</li>
            <li>Other Third</li>
            <li>Other Fourth</li>
            <li>Other Fifth</li>
            <li>Other Sixth</li>
        </ul>
    
        <script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
        <script>
            const $target = $(`ul[class='productWrapper']>li:nth-child(5)`)
            const $test = $(`<li class='inserted'>Inserted after fifth</li>`);
            $test.insertAfter($target);
        </script>
    </body>
    </html>
    

    After the page fully loads and the script is complete, this is how the page looks, which I believe is what you had in mind.

    screen after js executes