w3resource
jquery exercises

jQuery: Get a single element from a selection

jQuery core : Exercise-7 with Solution

Write a jQuery Code to get a single element from a selection.

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>Write a jQuery Code to get a single element from a selection</title>
</head>
<body>
<ui>
  <li>Html Tutorial</li>
  <li>Mongodb Tutorial</li>
  <li>Python Tutorial</li>
</body>
</html>

JavaScript Code :


var listItems = $( 'li' );
var rawListItem = listItems[1]; // or listItems.get(0)
var html = rawListItem.innerHTML;
console.log(html);

Sample Output :

 "Mongodb Tutorial"

Live Demo:

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


Contribute your code and comments through Disqus.

Previous: Write jQuery code to append a div element (and all of its contents) dynamically to the body element.
Next: Write a jQuery Code to add a tag at the beginning of the list item, containing the index of the list item.

What is the difficulty level of this exercise?



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