Reputation: 1514
How can i check for a custom data attribute attached to an element?
Here is my code.
how to see if the img
has any data-* attached to it?
<img id="myImg" src="#" data-tablet="img/xl.jpg" data-desktop="img/xl.jpg">
thanks.
Upvotes: 0
Views: 1900
Reputation: 1901
You can use Object.keys
Object.keys(document.getElementById('myImg').dataset).length
Upvotes: 0
Reputation: 1
Try
$.fn._hasData = function() {
return [].some.call(this[0].attributes, function(v, k) {
return /^data-/.test(v["name"])
})
};
console.log($("img")._hasData())
$.fn._hasData = function() {
return [].some.call(this[0].attributes, function(v, k) {
return /^data-/.test(v["name"])
})
};
console.log($("img")._hasData())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="myImg" src="#" data-tablet="img/xl.jpg" data-desktop="img/xl.jpg">
Upvotes: 0
Reputation: 884
function checkCustomData(objectId){
var attributes = document.getElementById(objectId).attributes;
var customDataStatus = false;
for (var x=0; x<attributes.length ; x++ ) {
if (attributes[x].name.indexOf("data-") == 0) var customDataStatus = true;
}
return customDataStatus
}
console.log(checkCustomData("myImg"))
Fiddle: http://jsfiddle.net/pyqd1fLg/
Upvotes: 0
Reputation: 321
I would iterate over the attributes while checking the string for "data-"
var el = document.getElementById("myImg");
for (var i = 0; i < el.attributes.length; i++){
// string comparison on 'data' with : el.attributes[i]
}
Upvotes: 0
Reputation: 59232
You can do it this way
if($('img').is('[data-tablet]'))
Or if you want to just want to check if there is a data-*
, you can do it this way by searching on the outerHTML of the element which you get either by using get
or using an indexer.
if($('img')[0].outerHTML.indexOf("data-") > -1)
Upvotes: 3