
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?
DOM (Document Object Model) updating using basic JavaScript might become difficult and needs more than one line of code. jQuery has simplified it through easy selectors and functions. Employing jQuery helps us ?- 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 ?