user1001176
user1001176

Reputation: 1163

jQuery to get text of first span of every li

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.

Upvotes: 11

Views: 18889

Answers (3)

Shafqat Masood
Shafqat Masood

Reputation: 2570

here is jsfiddle to get the elements using for loop

    $('ul.k-reset li').each(function(){
       var current = $(this).find('span:first');
        alert(current.text());
     });

Upvotes: -1

Ram
Ram

Reputation: 144659

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();

Upvotes: 15

Guffa
Guffa

Reputation: 700192

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();

Upvotes: 4

Related Questions