最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing Attributes to Append function in Jquery Not Working - Stack Overflow

programmeradmin0浏览0评论

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>

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>
Share Improve this question asked Mar 31, 2013 at 10:39 S. A. MalikS. A. Malik 3,6556 gold badges40 silver badges59 bronze badges 1
  • Why did you expect it to work at all? The documentation does not mention anything in this regard: api.jquery.com/append. – Felix Kling Commented Mar 31, 2013 at 10:52
Add a comment  | 

4 Answers 4

Reset to default 14

.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>

Try this:

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

You could do

$(this).append('<span class="someClass">some text</span>');

The second parameter for append is (and I quote jQuery documentation) :

One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.

发布评论

评论列表(0)

  1. 暂无评论