Rajesh S
Rajesh S

Reputation: 1

how to get <li> from <ul> with tag in jquery

<ul id="chapters">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>

var a = $("#chapters li");    

How do I get the variable a so as it contains the following result:

a = "<li>One</li>    <li>Two</li>    <li>Three</li>"

Upvotes: 0

Views: 58

Answers (3)

Arun CM
Arun CM

Reputation: 3435

var a = $('#chapters').children( $('li'))
console.log(a.toArray());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="chapters">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>

You can use jQuery childer method.

$('#chapters').children( $('li'))

Upvotes: 1

nicael
nicael

Reputation: 19034

What you are trying to do is to get the HTML contents of #chapters.

You are going to use

$("#chapters").html()

var a = $("#chapters").html();
console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="chapters">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>

You could also remove the newlines and trim the whitespace to get the exact result:

$("#chapters").html().replace(/\n/g,'').trim();

var a = $("#chapters").html().replace(/\n/g,'').trim();
console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="chapters">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>

Upvotes: 1

bloC
bloC

Reputation: 526

$('#chapters').find('li')

This should do the trick.

Upvotes: 0

Related Questions