Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to get text of first span of every li

Tags:

jquery

I am trying to get the first value of span under different li elements. My HTML markup is as follows...

<div class="mipartrel">
    <div class="k-multiselect-wrap k-floatwrap">
        <ul role="listbox" unselectable="on" class="k-reset">
            <li class="k-button">
                <span>bat</span>
                <span class="k-icon k-delete">delete</span>
            </li>
            <li class="k-button">
                <span>ball</span>
                <span class="k-icon k-delete">delete</span>
            </li>
        </ul>
    </div>
</div>

I used the following jQuery code to get the text of all the span elements...

var getdata=$('.mipartrel ul li span').first().text();

...but I am only getting the value "bat". I need each and every value from the first span of every li.

like image 950
user1001176 Avatar asked Apr 29 '13 11:04

user1001176


2 Answers

The first method only returns the first matched element, you can use the find method:

var textArray = $('.mipartrel ul li').find('span:first').map(function(){
    return $(this).text();
}).get(); // ["bat", "ball"]

var textString = textArray.join(); // "bat, ball"

http://jsfiddle.net/s797E/

Or:

var getdata = $('.mipartrel ul li').find('span:first').text();
like image 145
undefined Avatar answered Nov 16 '22 12:11

undefined


Use the first-child selector to get the spans that are the first child of their parent:

var getdata = $('.mipartrel ul li span:first-child').text();

Demo: http://jsfiddle.net/Guffa/38NN5/

The text method will get the text from all elements as a single string. If you want it as an array, you need to get each text separately:

var getdata = $('.mipartrel ul li span:first-child').map(function(){
  return $(this).text();
}).get();
like image 28
Guffa Avatar answered Nov 16 '22 14:11

Guffa