Programmatically adding to a list item inside an accordion section Jquery

2359 views javascript
5

I have a jquery accordion that has several sections (three in the code below). Inside each section I have 3 items in an unordered list. How can I dynamically add to a given section (say section 2) and add another item ("List item four") to section 2's list?

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Accordion - Default functionality</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"> 
</script>
    <script>
        $( function() {
            $( "#accordion" ).accordion();
        } );
    </script>
</head>
<body>

<div id="accordion">
    <h3>Section 1</h3>
    <div>
        <ul class="section1">
            <li><a href="www.google.com"> List item one</a></li>
            <li><a href="www.google.com"> List item two</a></li>
            <li><a href="www.google.com"> List item three</a></li>
        </ul>
    </div>
    <h3>Section 2</h3>
    <div>
        <ul class="section2">
            <li><a href="www.google.com"> List item one</a></li>
            <li><a href="www.google.com"> List item two</a></li>
            <li><a href="www.google.com"> List item three</a></li>
        </ul>
    </div>
    <h3>Section 3</h3>
    <div>
        <ul class="section3">
            <li><a href="www.google.com"> List item one</a></li>
            <li><a href="www.google.com"> List item two</a></li>
            <li><a href="www.google.com"> List item three</a></li>
        </ul>
    </div>
</div>


</body>
</html>

answered question

1 Answer

3

You can use jQuery to append additional elements to each ul

$('.section2').append(`<li><a href="www.google.com"> List item four</a></li>`)

posted this

Have an answer?

JD

Please login first before posting an answer.