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

Asked

Viewed 1,292 times

2

In this code:

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

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

2 answers

4


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

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

Will you return true or false.

More information here: W3schools - hasAttribute.

  • I was able to solve the problem using hasAttribute(), https://jsfiddle.net/rsf6mn9n/

  • @Matheusmiranda then if Douglas' answer solved your problem, please mark it as correct. We are not a forum, we are a Q&A, please take the tour: http://answall.com/tour to understand how the site works

  • Thanks @Guilhermenascimento, I saw document how the site works.

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

  • Hi Lucas Costa, this also works, thanks for the reply.

Browser other questions tagged

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