I have the following list:
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
How can I use jQuery to remove the first element of this list (i.e. the number 1) and leave the remaining elements intact?
I'd have thought this have quite a simple solution but it's proving harder than I expected to answer.
Answer: Use the JavaScript substring() method You can use the JavaScript substring() method to remove first character form a string. A typical example is removing hash ( # ) character from fragment identifier.
In jQuery, in order to remove element and content you can use anyone of the following two jQuery methods: Methods: remove() – It is used to remove the selected element (and its child elements). empty() – It is used to removes the child elements from the selected element.
length > 0){ var anotherToDo = $("<p>" + newToDo + "</p>"); $("#toDoList"). append(anotherToDo); $("#newToDo"). val(" "); // later when you want to delete it anotherToDo. remove(); } }); });
To remove elements and its content, jQuery provides two methods: remove(): It removes the selected element with its child elements. empty(): It removes the child element from the selected elements.
$('#list li').first().remove();
jsFiddle example
Ref:
You could also accomplish a similar effect using pure CSS3 (no JavaScript) with:
#list li:nth-child(1) {
display:none;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With