Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Attributes to Append function in Jquery Not Working

I am trying to pass attributes to a jquery append function. It appends the html but does not append the attributes. There are no errors shown in the console either. Html Code :

    <li>First Item</li>
    <li>Second Item</li>

Javascript Code :

    $('li').each(function(){
        $(this).append('<span></span>', {
            text: 'some text',
            class: 'someClass'
        })
    });

I want the HTML to look like

 <li>First Item <span class="someClass">some text</span></li>
 <li>Second Item Item <span class="someClass">some text</span></li>
like image 864
S. A. Malik Avatar asked Dec 09 '22 16:12

S. A. Malik


2 Answers

.append() is a Method which accepts string arguments or a function .append("<p>A</p>", "<p>B</p>") or .append(function() {}); - so you're passing an invalid Object as argument.

Instead, use $("<HTMLTag>", {...options}) to Create New Elements

$("li").each(function(){

  $("<span>", {
    class: "someClass", 
    text: " some text",
    appendTo: this,
  });
  
});
<ul>
  <li>First Item</li>
  <li>Second Item</li>
</ul>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
like image 146
Roko C. Buljan Avatar answered Dec 11 '22 10:12

Roko C. Buljan


Try this:

$('li').each(function(){
        $('<span/>',{
            text: 'some text',
            class: 'someClass'
        }).appendTo(this);
});
like image 45
Mohamed AbdElRazek Avatar answered Dec 11 '22 08:12

Mohamed AbdElRazek