Check date attribute

Asked

Viewed 155 times

1

Can you tell me if it is possible to check whether an image has an attribute data? This only with the img selector, not by ID or class.

What I got:

<img data-src='http//.......'/>

if($('img').data('src)){
  alert();
}

I would just like to check whether such an image has a date attribute or not.

Example:

<img data-src='http//.......'/>

or not:

 <img src='http//.......'/>

Thanks.

1 answer

0


You can use the method .hasAttribute() Javascript that already returns a boolean if the attribute exists or not in the element:

document.getElementsByTagName("img")[0].hasAttribute("data-src") // retorna true ou false

Or other methods to verify that it is different from undefined. In these methods, the code will attempt to take the value of data-src. If the attribute does not exist, it will return undefined:

// JS método 1
if( document.getElementsByTagName("img")[0].hasAttribute("data-src") ){
   console.log("tem com JS puro - método 1");
}

// jQuery
if( $("img").data("src") !== undefined ){
   console.log("tem com jQuery");
}

// JS método 2 (IE11+)
if( document.getElementsByTagName("img")[0].dataset.src !== undefined ){
   console.log("tem com JS puro - método 2");
}

// JS método 3
if( document.getElementsByTagName("img")[0].getAttribute("data-src") !== undefined ){
   console.log("tem com JS puro - método 3");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img data-src />

But this will only work if you have only 1 <img> on the page. If you have more than one, you will need to make a loop to iterate each of the elements, otherwise it will only take the first element <img>.

  • Thank you very much now it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.