简体   繁体   中英

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?

Try to use has attribute selector at this context,

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

DEMO

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 
}

you can do

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

then check for existence

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM