Adam Pietrasiak
Adam Pietrasiak

Reputation: 13194

Detect elements with attribute without value

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?

Upvotes: 3

Views: 4391

Answers (3)

Mike
Mike

Reputation: 6050

you can do

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

then check for existence

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

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

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 
}

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to use has attribute selector at this context,

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

DEMO

Upvotes: 3

Related Questions