Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for existence of specific data attribute value

I'm trying to select a DOM element with a specific attribute value. I'd like to avoid an each() loop, but all I've seen in jQuery is the ability to detect the existence of the data attribute, not its value. So, I want to accomplish something like this:

if ($('.item[data-index="' + indexVal + '" ]'){
  //if an .item with the data-index value of indexVal exists...
}
like image 840
mheavers Avatar asked Aug 29 '13 19:08

mheavers


People also ask

How do you know if an element has a specific attribute?

The Element. hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not.

How do you get the value of a data attribute?

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to "5" .

How do you check if data attribute exists in Javascript?

The hasAttribute() method returns true if the attribute exists, otherwise false .


2 Answers

missing ) and $(selector) should not be put in a if condition. it is always true even it does not select anything.

if ($('.item[data-index="' + indexVal + '" ]').length) {
like image 114
Moazzam Khan Avatar answered Nov 06 '22 22:11

Moazzam Khan


try this:

if ($('.item[data-index="' + indexVal + '" ]').length > 0){

}
like image 24
sd1sd1 Avatar answered Nov 06 '22 22:11

sd1sd1