0

Assume there are three classes

<div class="hello world_1"></div>
<div class="hello world_2"></div>
<div class="hello world_3"></div>

I want to get the class name "world_1","world_2" and "world_3" based on "hello". The code:

$('.hello').each(function(){
  this.attr('class');
});

got error saying:

TypeError: Object #<HTMLDivElement> has no method 'attr'

I experimented a little bit and found

$('.hello:first').attr('class')

works while

$('.hello')[0].attr('class')

raises the above error.

Could anyone explain why it happened and how can I get what I want?

Thanks

4 Answers 4

8

You need to wrap the this, like so...

$('.hello').each(function(){
  $(this).attr('class');
});

jQuery provides this as a reference to a native DOM element. To able to call jQuery methods on it, wrap it with the jQuery constructor.

If you want to match class of pattern world_n, you could use...

var matches = $(this).attr('class').match(/(?:^|\s)world_\d+(?:\s|$)/);
Sign up to request clarification or add additional context in comments.

4 Comments

@alex Can you elaborate, why /(?:^|\s)world_\d+(?:^|\$)/ (which doesn't work at all ) and not simple /world_\d+/ ?
@Engineer That's a massive fail on my behalf. I'll fix it.
@alex I just want to know, why do you need that "complicated stuff" ?
@Engineer It depends. You may have another class with world_ in it that you don't want to match.
1

try

$('.hello').each(function(){
  $(this).attr('class');
});

Comments

1

Whats happening is that the jquery each function sets the this to be the DOM element, and doesn't 'prewrap' the jquery wrapper around this element.

So like alex has said, simply wrapping it again will give you want you want.

Comments

0

To get only the world_class names, you'll need to do a string replace and remove whitespaces using $.trim:

$('.hello').each(function(){
  $.trim($(this).attr('class').replace('hello', ''));
});

Comments

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.