w3resource
jquery exercises

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?



New Content: Composer: Dependency manager for PHP, R Programming