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...
}
The Element. hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not.
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" .
The hasAttribute() method returns true if the attribute exists, otherwise false .
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) {
try this:
if ($('.item[data-index="' + indexVal + '" ]').length > 0){
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With