Reputation: 31
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
}));
Upvotes: 3
Views: 220
Reputation: 3841
If you want to add this 'list-group-item' then change it to
class: 'list-group-item'
Upvotes: 0
Reputation: 19070
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>
Upvotes: 1
Reputation: 26450
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'
}));
});
Upvotes: 0