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 :
JavaScript
x
3
1
<li>First Item</li>
2
<li>Second Item</li>
3
Javascript Code :
JavaScript
1
7
1
$('li').each(function(){
2
$(this).append('<span></span>', {
3
text: 'some text',
4
class: 'someClass'
5
})
6
});
7
I want the HTML to look like
JavaScript
1
3
1
<li>First Item <span class="someClass">some text</span></li>
2
<li>Second Item Item <span class="someClass">some text</span></li>
3
Advertisement
Answer
.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
JavaScript
1
9
1
$("li").each(function(){
2
3
$("<span>", {
4
class: "someClass",
5
text: " some text",
6
appendTo: this,
7
});
8
9
});
JavaScript
1
6
1
<ul>
2
<li>First Item</li>
3
<li>Second Item</li>
4
</ul>
5
6
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>