Use hasAttribute() Get Typeerror: hasAttribute Is Not a Function

I try to find out the number of <img> elements that do not have "style" attribute in a HTML file by using JavaScript.

My solution: find out numbers of <img> tags as "imgCount", then get number of <img> tags with "style" attribute as "imgStyCount". After that, use "imgCount" minus "imgStyCount" to get the final result that I wish to know.

However, something goes wrong. My browser keep told me

TypeError: document.getElementsByTagName(...)[K].hasAttribute is not a function

At the if statement. And the weird thing is, the alert(document.getElementsByTagName("img")[k].hasAttribute("style") show the if statement result is TRUE. How it can be like not a function and give the true value?

var imgCount = 0;

var imgStyCount = 0;

var result;

for (k in document.getElementsByTagName("img")) {

  if (document.getElementsByTagName("img")[k].hasAttribute("style") == true) {

    alert(document.getElementsByTagName("img")[k].hasAttribute("style"));

    console.log("    <img> =: ", document.getElementsByTagName("img")[k].style);

    imgStyCount++;

  }

  imgCount++;

}
result = imgCount - imgStyCount;
<img height="150px" src="" style="vertical-align:middle;margin-right:20px;" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
4

3 Answers

Here's a simple way without using loop.

You can use querySelectorAll with attribute selector

document.querySelectorAll('img[style]') will select all the <img> elements on the page having style attribute.

var result = document.querySelectorAll('img').length - document.querySelectorAll('img[style]').length;

alert(result);
<img height="150px" src="" style="vertical-align:middle;margin-right:20px;" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
1

Use for-loop to iterate image elements than for-in

var imgStyCount = 0;
var elems = document.getElementsByTagName("img");
for (var k = 0; k < elems.length; k++) {
  if (elems[k].hasAttribute("style")) {
    imgStyCount++;
  }
}
var result = elems.length - imgStyCount;
alert(result);
<img height="150px" src="" style="vertical-align:middle;margin-right:20px;" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />

Fiddle demo

0
<span medium-img>Whatever</span>

alert($('span').is('[medium-img]')); // Returns true
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest