2

I'm relatively new with JQuery. Let's say I have a divs structure like this:

<div class='quater'>
  <div id='a' class='target'></div>
  <div id='b' class='target'></div>
  <div id='c' class='no_target'></div>
</div>

and i would like to ad an onClick function that retrieve class "target" id's.

I tried with:

$('.quater').on('click', function(){
    var $value = $(this).children('.target');
    $value.each(function(){
        alert(this.attr('id'));
   });
});

but it returns: undefined is not a function

What is the right way to iterate through these elements to retrieve their ids?

1 Answer 1

4

Try to invoke the .attr() function over wrapped jQuery object,

alert($(this).attr('id'));

this is a plain JavaScript object and it won't contain a member function called .attr()

Full code would be,

  $('.quater').on('click', function() {
    var $value = $(this).children('.target');
    $value.each(function() {
      alert($(this).attr('id'));
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class='quater'>test
  <div id='a' class='target'></div>
  <div id='b' class='target'></div>
  <div id='c' class='no_target'></div>
</div>

Sign up to request clarification or add additional context in comments.

4 Comments

TNX a lot, obviously works like a charm, so is it the right way to iterate through JQuery selected elements? I mean is it correct to use a $variable to save the collection and iterate through it with .each() function?
@Plastic Yes it is.. And by the way glad to help.!
@Plastic Yeah caching a traversed collection of elements in a variable is usually a good practice to follow. Keep on doing that in your upcoming projects.
Thanks again, your answer will be accepted in 5 mins ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.