prog1011
prog1011

Reputation: 3495

How to find each li from Div and how to get text of each <li> tag?

I am using below Html code and I want to get all the <li> tags from the <div id="divSelect"> and I want to get text from all li tags.

HTML

Please help , how to use .each() and .find() using JQuery.

Thanks

Upvotes: 0

Views: 9178

Answers (7)

Devendra Soni
Devendra Soni

Reputation: 1934

Hey I have used your html and wrote a jQuery function which is using .each and .find to fetch all the li from the DIV.

we should use .find where we can use, its recommened by jQuery.(its performance is good if it is user wisely)

html code:-

<div id="divSelect" class="custom dropdown">
    <ul>
<li>text 1</li>
<li>text 2</li>
<li>text 3</li> 
    </ul>
</div>

and javascript code is:-

 $("#divSelect").find("li").each(function()
    {
       var $li=$(this);                
       alert($li.text()) 
    });

thanks

Upvotes: 6

Balachandran
Balachandran

Reputation: 9637

Use map in jquery to collect all data ,this.outerHTML in javascript to return the html element

    var data=$("#divSelect ul li").map(function(){
        return this.outerHTML;
    }).get();
alert(data);

DEMO

Upvotes: 0

sarath
sarath

Reputation: 56

$("#divSelect").find("li").each(function(){
  alert($(this).html());
  });

Upvotes: 0

Sudhanshu Saxena
Sudhanshu Saxena

Reputation: 1199

This can be achieved by

$("#divSelect ul li").each(function(index){
alert ( index + ": " + $( this ).text() );
});

Upvotes: 0

Amin Jafari
Amin Jafari

Reputation: 7207

try this:

var liText='';
$('#divSelect ul li').each(function(){
    liText+=$(this).html();
});

liText will contain all the "li"s texts.

Upvotes: 0

Alex Char
Alex Char

Reputation: 33228

$("#divSelect > ul > li").text();

With this you get text from all li elements.

fiddle

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

To get them in array,You can use:

var alllitexts=$('#divSelect ul li').map(function(){
  return $(this).html();
}).get();

using each and getting them individually:

$("#divSelect ul li").each(function(){
  alert($(this).html());
});

Upvotes: 0

Related Questions