0

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.

Cloudboy22
  • 1,496
  • 5
  • 21
  • 39
  • possible duplicate of [jQuery hasAttr checking to see if there is an attribute on an element](http://stackoverflow.com/questions/1318076/jquery-hasattr-checking-to-see-if-there-is-an-attribute-on-an-element) – Mr. Alien Nov 24 '14 at 14:44

5 Answers5

3

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)
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • i mean to check if my image has just about any data attached to it. – Cloudboy22 Nov 24 '14 at 14:46
  • can you tell me what does the second code mean.I mean can you explain it.Thanks. – Cloudboy22 Nov 24 '14 at 15:56
  • @MarcAndreJiacarrini that takes the html structure of the img and then searches if there is any "data-" string in the string and returns true if it is present else false – Amit Joki Nov 24 '14 at 16:00
  • @MarcAndreJiacarrini outerHTML returns whole structure for given element, not only attributes - so for example if your image src or name will contain "data-", this code will also return true. – Marian Gibala Nov 25 '14 at 13:30
0

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] 
}
Mark Labenski
  • 311
  • 3
  • 10
0
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/

Marian Gibala
  • 874
  • 7
  • 9
0

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">
guest271314
  • 1
  • 15
  • 104
  • 177
0

You can use Object.keys Object.keys(document.getElementById('myImg').dataset).length

Inc33
  • 1,747
  • 1
  • 20
  • 26