How to check if HTML tag has certain attribute with JS?

2

In this code:

<img id="SizeImage1" style="cursor:pointer">

As you can see, it has no attribute src . How can I tell if a tag has src or not using JavaScript?

    
asked by anonymous 22.11.2016 / 15:15

2 answers

4

You can check using the hasAttribute () method, see below:

document.getElementById('SizeImage1').hasAttribute('src');

It will return true or false .

More information here: W3Schools - hasAttribute .

    
22.11.2016 / 15:19
3

Another way is to get the value of src , then check whether it is empty or not:

var src1 = document.getElementById("SizeImage1").src
  , src2 = document.getElementById("SizeImage2").src;

// verifica se está null, '', undefined, 0
if (!src1)
 console.log("Primeiro está vazio");

if (!src2)
console.log("Segundo está vazio");
<img id="SizeImage1" style="cursor:pointer">
<img id="SizeImage2" style="cursor:pointer" src="google.com">
    
22.11.2016 / 15:19