Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  15] [ 2]  / answers: 1 / hits: 24669  / 8 Years ago, fri, april 1, 2016, 12:00:00

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=Http://flax.nzdl.org/images/ngf.jpeg style=vertical-align:middle;margin-right:20px; />
<img src=Http://flax.nzdl.org/images/abc.jpg />
<img src=Http://flax.nzdl.org/images/fbc.jpg />
<img src=Http://flax.nzdl.org/images/agc.jpg />
<img src=Http://flax.nzdl.org/images/abt.jpg />




More From » html

 Answers
2

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=Http://flax.nzdl.org/images/ngf.jpeg style=vertical-align:middle;margin-right:20px; />
<img src=Http://flax.nzdl.org/images/abc.jpg />
<img src=Http://flax.nzdl.org/images/fbc.jpg />
<img src=Http://flax.nzdl.org/images/agc.jpg />
<img src=Http://flax.nzdl.org/images/abt.jpg />





Fiddle demo


[#62733] Wednesday, March 30, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taliac

Total Points: 84
Total Questions: 114
Total Answers: 114

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
taliac questions
Sun, Mar 21, 21, 00:00, 3 Years ago
Tue, May 12, 20, 00:00, 4 Years ago
Mon, Jan 13, 20, 00:00, 4 Years ago
;