Rouge
Rouge

Reputation: 4239

How to find the element by classname

I am trying to do a loop to check all the elements with a class selector.

I have

html

<div class='label'>aaaa</div>
<div class='label'>bbbb</div>
<div class='label'>cccc</div>
<div class='label'>dddd</div>

 var pre=$('.label')

    pre.each(function(e){
        console.log(e);
    })

but it doens't show the element (aaaa,bbbb..etc).

How do I do this? Thanks a lot

Upvotes: 0

Views: 61

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

var pre = $('.label');

pre.each(function(i, el){
    console.log( el );
    // OR
    console.log( this ); // will give you the element

    // suppose to get text
    console.log( $(el).text() ); // or $(this).text()
});

DEMO

First argument of .each() is index and second argument is value (here your target element).

Read more about .each().

Upvotes: 3

Brad Christie
Brad Christie

Reputation: 101604

For answering's sake, the .each method in jQuery passes two values (amongst context) when it's called:

.each(function(index,value){
});

So my providing only e in your each function you're only asking for the index argument. You'd need to supply two arguments to get the actual element or value.

However, when iterating over elements the context of the interative function is also passed the element. So:

$('.label').each(function(index,element){
  // element == this
});

So if you don't want to supply the second argument you can just refer to this within the function.

Upvotes: 1

Related Questions