FlyingCat
FlyingCat

Reputation: 14250

How to get the value from a class element?

I am trying to get the selected class text.

I have

for (var i=0; i<$('.toys').length; i++){

       if($('.toys')[i].text()=='lego'){
         alert('got it');
         return false;
      }
    }

html

<div class='toys'> toya  </div>
<div class='toys'> lego  </div>
<div class='toys'> toyb  </div>
<div class='toys'> toyc  </div>

I got an error saying the Object # has no method 'text'

How do I fix this? Thanks for the help!

Upvotes: 1

Views: 58

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

First of all you should cache your results to avoid repeating queries to the DOM.

The problem with your code is that using [] returns the raw DOM element (not a jquery object), and DOM elements do not have the .text() method. You should use .eq(i) instead of [i].

As others have mentioned, though, a more proper way would be to use .each() or alternatively to use .filter()

var wanted = $(".toys").filter(function() {
    return $.trim($(this).text()) === 'lego';
});
if (wanted.length){
  alert('got it'); // or do whatever you want with the wanted element..
}

Upvotes: 2

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

You can (and should) use a jQuery $.each() loop to iterate over collections, like this:

$(".toys").each(function() {
    if($(this).text() == "lego") {
        alert("got it!");
        return false;
    }
});

Upvotes: 1

Related Questions