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.

1

5 Answers 5

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)
Sign up to request clarification or add additional context in comments.

4 Comments

i mean to check if my image has just about any data attached to it.
can you tell me what does the second code mean.I mean can you explain it.Thanks.
@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
@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.
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] 
}

Comments

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/

Comments

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">

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.