3

Lets say I've got

<div class="some-class" selected></div>

I'm trying to say if it has attr 'selected', but

$(".some-class").attr("selected") //undefined
$(".some-class").is("*[selected]") // false

Am I able to say if it has selected attrbute even if it has no value?

5
  • 2
    that's not valid markup Commented Jun 26, 2014 at 8:35
  • @billyonecan why are you saying that this is an invalid markup..? What if user need to set some unique identity to that element by means of that attibute..? Commented Jun 26, 2014 at 8:39
  • @RajaprabhuAravindasamy because a div doesn't have a selected attribute Commented Jun 26, 2014 at 8:39
  • @billyonecan Yeah that's right, div does not have to do anything with that attribute.. but it might be useful for implementing some other logics right..? :) Commented Jun 26, 2014 at 8:40
  • 2
    @RajaprabhuAravindasamy in that case you'd use data- attributes, or you could just use a class Commented Jun 26, 2014 at 8:41

3 Answers 3

3

Try to use has attribute selector at this context,

$(".some-class").is("[selected]")

DEMO

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

3 Comments

is() returns a boolean (true/false), .some-class[selected] would return the element itself
@dandavis then we have to extract its length property.. like if($('.some-class[selected]').length)
@RajaprabhuAravindasamy I didn't downvote. This answer is correct, although the markup in the question is invalid
1

you can do

$(".some-class[selected]")

then check for existence

let element = $(".some-class[selected]");
if (element.length)

Comments

0

Try this : Write a function hasAttr() which checks if provided attribute it undefined or not. If it is undefined means attribute does not exist.

$.fn.hasAttr = function(name) {  
   return this.attr(name) !== undefined;
};

 if($('.some-class').hasAttr('selected'))
{
  //do your stuff 
}

1 Comment

I think it would be more helpful for the OP and further visitors if you would add some explanations for your intention.

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.