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!
– Caio Lourençon