w3resource

jQuery: Add a tag at the beginning of the list item

jQuery core : Exercise-8 with Solution

Write a jQuery Code to add a tag at the beginning of the list item, containing the index of the list item.

Sample Data :

<body>
<ui>
<li>Html Tutorial</li>
<li>Mongodb Tutorial</li>
<li>Python Tutorial</li>
</body>

Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Add a tag at the beginning of the list item</title>
</head>
<body>
<ui>
<li>Html Tutorial</li>
<li>Mongodb Tutorial</li>
<li>Python Tutorial</li>
</body>
</html>

JavaScript Code :

$( 'li' ).each(function( index, elem ) {
    $( elem ).prepend( '' + index + ': ' );
});

Sample Output:

  • 0: Html Tutorial
  • 1: Mongodb Tutorial
  • 2: Python Tutorial

Live Demo:

See the Pen jquery-core-exercise-8 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Write a jQuery Code to get a single element from a selection.
Next: Write jQuery Code to change the hyperlink and the text of a existing link

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/jquery-exercises/jquery-core-exercise-8.php