
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add New List Element Under a UL Using jQuery
In this article, we will learn to add a new list element under a "<ul>" using jQuery. jQuery is a popular JavaScript library that simplifies HTML manipulation, event handling, and animations. One of its practical applications is dynamically adding elements to a webpage without requiring a full page reload.
Why Use jQuery?
Updating the DOM (Document Object Model) with plain JavaScript can be cumbersome and require multiple lines of code. jQuery simplifies this process with its easy-to-use selectors and methods. Using jQuery allows us to ?
- Select elements efficiently.
- Handle events seamlessly.
- Modify the DOM dynamically.
To add a new list element under an "<ul>" element, use the jQuery append() method.
Set input type text initially ?
Value: <input type="text" name="task" id="input">
Now on the click of a button, add a new list element using the val() and append() methods in jQuery ?
$(document).ready(function(){ $('button').click(function() { var mylist = $('#input').val(); $('#list').append('<li>'+mylist+'</li>'); return false; }); });
The jQuery script waits for the document to be ready, then listens for a click event on the button ?
-
$('#input').val() retrieves the value entered in the input field.
- $('#list').append('<li>'+mylist+'</li>')dynamically adds a new list item () to the unordered list.
- return false; prevents the default form submission behavior to avoid page reloads.
Example
Below is an example of adding a new list element under a "<ul>" using jQuery ?
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('button').click(function() { var mylist = $('#input').val(); $('#list').append('<li>'+mylist+'</li>'); return false; }); }); </script> </head> <body> <form> Value: <input type="text" name="task" id="input"> <button>Submit</button> <br> <p>Add a value above and click Submit to add a new list.</p> <ul id="list"> </ul> </form> </body> </html>
Output
Enter the values and press enter to display it as an unordered list item ?
Conclusion
Using jQuery, we can efficiently add new elements to an HTML list with minimal code. This method enhances user experience by allowing dynamic content updates without page reloads. By ensuring that only valid inputs are added, we maintain a clean and functional list.