How to add 'list-group-item' class while appending an element with jquery?
After appending an <li>
to the <ul id="todoList">
, the class property is not working as i expected.
$("#todoList").append($('<li>', {
text: $('#todoInput').val(),
class: $('list-group-item') // this is not working
}));
You can do:
$("#todoAddBtn").on("click", function() { $("#todoList").append($('<li>', { text: $('#todoInput').val(), class: 'list-group-item' // <-- Class name should be an string })); $('#todoInput').val(''); // Clear input.. });
.list-group-item { color: blue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="todoList"></ul> <input id="todoInput"> <button id="todoAddBtn">Add</button>
When you do class: $('list-group-item')
, you're basically creating an object that you add to the class
. You just want a string that is the class-name, and not an object. All you need is class: 'list-group-item'
.
$("#todoAddBtn").on("click", function() {
$("#todoList").append($('<li>', {
text: $('#todoInput').val(),
class: 'list-group-item'
}));
});
如果要添加此“list-group-item”,请将其更改为
class: 'list-group-item'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.