Logical Error Logical Error - 6 months ago 15
HTML Question

not getting correct way of adding li elements to ul using jquery

I want to add

li
element to
ul
in this way

<li>
<div>
<span>Ad</span>
</div>
<div>
<span><a href="#">A title.</a></span>
<span>Some text here</span>
</div>
</li>


but through this code below



$(document).ready(function() {
$('#notify').click(function(e) {
$('#ul_addon').append(
$('<li><div>').append(
$('<span>Ad</span>'),
$('</div>'),
$('<div>').append(
$('<span><a href="#">A title.</a></span>'),
$('<span"></span>').html("New Text")
),
$('</div></li>')
)
);
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul id="ul_addon">
<li>
<div>
<span>Ad</span>
</div>
<div>
<span><a href="#">A title.</a></span>
<span>Some text here</span>
</div>
</li>
</ul>

<button id="notify" type="button">Add</button>





I'm getting

<li>
<div></div>
<span>Ad</span>// this <span> is out of the <div> above
<div>
<span><a href="#">A title.</a></span>
<span>Some text here</span>
</div>
</li>


I want to have
<span>
in
<div>
element as

<div>
<span>Ad</span>
</div>


but don't have idea of getting the desired result.

Disclaimer : I'm newbie in JS world please don't mind if you find this stupid.

Answer

You need to append div to li instead of creating div like below

$('<li><div>') 

// will create elements and it will look like <li><li><div></div>

Use the below code instead

    $(document).ready(function() {
      $('#notify').click(function(e) {
        $('#ul_addon').append(
          $('<li>').append(
            $('<div><span>Ad</span></div>'),
            
            $('<div>').append(
              $('<span><a href="#">A title.</a></span>'),
              $('<span"></span>').html("New Text")
            ),
            $('</div></li>')
          )
        );
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <ul id="ul_addon">
      <li>
        <div>
          <span>Ad</span>
        </div>
        <div>
          <span><a href="#">A title.</a></span>
          <span>Some text here</span>
        </div>
      </li>
    </ul>

    <button id="notify" type="button">Add</button>