0

I have some element that goes like this

<div class="section current" section="Email">

</div>

What i need is to check that section Email have class CURRENT, and do something like

if ($('.section').attr(section == Email).hasClass('current')){
 // Do something...
}

I know this is wrong syntax but i want just to simple show what i need?

3
  • 1
    The .attr() method is used for getting or setting an attribute, it's not used for finding an element that matches an attribute. Do you bother to read the documentation of functions before you use them, or do you just pray that they'll do what you want? Commented Jul 31, 2014 at 10:14
  • section="" is not valid html. Change it to data-section="" to make it valid and persist same behaviour. Commented Jul 31, 2014 at 10:15
  • In addition, even if it did perform searching, the argument (section == Email) wouldn't do what you want. That compares a variable named section with a variable named Email, and passes either true or false to the attr method. That's just basic Javascript syntax, nothing to do with jQuery or selectors. Commented Jul 31, 2014 at 10:18

3 Answers 3

1

You need to use attribute-equals-selector:

if($('.section[section="Email"]').hasClass('current')){
  //do something
}

Demo

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

3 Comments

In case you will change it to data-section="Email", just modify the selector like this: $('.section[data-section="Email"]')
@HenriHietala:section is not data attribute. so there is no need to use data.
as I commented in the question, section="" is not valid html but data-section="" is valid (html5). Of course there's no need to do valid html since it works like that also.
0

You can take a look at jQuery's attribute selector:

http://api.jquery.com/attribute-equals-selector/

I would guess you can solve your problem with this:

if($(".section[section='Email]" ).hasClass("current")){/**CODE**/}

Hope this helps!

Comments

0

You could try like this also.

if ($('.section[section="Email"].current').length > 0) {

}

2 Comments

That won't work. That tests a jQuery object, which is always truthy, even if it doesn't match anything. You need if($('.section[section="Email"].current').length > 0){
Yes Barmar. thankyou. i just forgot to right it. Thanks anyway

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.