Alice
Alice

Reputation: 331

How to get nth-child value with jquery

I got an unordered list like this:

<ul>
 <li>One</li>
 <li>Two</li>
 <li>Three</li>
 <li>Four</li>
</ul>
<div id='output'></div>

I have just read about nth-child in javascript and I got a small question: How can I print out the value of the nth-child in the output div? I do it like this and it returns [object HTMLDivElement]

var el=$("ul li:nth-child(2)").val();
  $('#output').text('The second child is: '+el[0]);
  console.log(el);

Upvotes: 1

Views: 1609

Answers (3)

Nakul Pritam
Nakul Pritam

Reputation: 76

You need to read the innerText of the li instead of the value which is not present in this case.

var el=$("ul li:nth-child(2)");
  $('#output').text('The second child is: '+el[0].innerText);
  console.log(el[0].innerText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
 <li>One</li>
 <li>Two</li>
 <li>Three</li>
 <li>Four</li>
</ul>
<div id='output'></div>

Upvotes: 1

user3483203
user3483203

Reputation: 51165

$('#output').text('The second child is ' + $("ul li:nth-child(2)").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
 <li>One</li>
 <li>Two</li>
 <li>Three</li>
 <li>Four</li>
</ul>
<div id='output'></div>

Upvotes: 1

Kristian Lilov
Kristian Lilov

Reputation: 610

You probably want to take the text value :

var el = $("ul li:nth-child(2)").text();

And output it like this :

 $('#output').text('The second child is: ' + el);

Upvotes: 2

Related Questions