Help - Search - Members - Calendar
Full Version: document.getElementsByClassName() - how to iterate
HTMLHelp Forums > Programming > Client-side Scripting
pandy
Going nuts over this. The worst thing is I think I've done it before. Anyway, I want to somehow get to all elements with a certain class and do stuff to them.

First I tried a simple for loop. Didn't work. Then the google nightmare began. Somewhere it was suggested it must be done in reverse, from the last item to the first. Didnt' work either.

I've learnt that document.getElementsByClassName() doesn't return an array but a nodelist and the item() method was suggested. Didn't work either.
https://developer.mozilla.org/en-US/docs/Web/API/NodeList

Here's a simple example that's of course isn't working. cool.gif

HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>
<title>Not worth it</title>



<script type="text/javascript">
<!--

function blah()
{
var idiots = document.getElementsByClassName("dumb");
for (var i = 0; i < idiots.length; i++) {
idiots.item(i).style.color = 'red';
}


document.onload = blah;
//-->
</script>

</head>


<body>

<p>
This is...<span class="dumb">dumb!</span></p>
<p>
This is...<span class="dumb">dumb!</span></p>
<p>
This is...<span class="dumb">dumb!</span></p>


</body>
</html>


Help! sad.gif
Christian J
QUOTE(pandy @ Sep 6 2020, 10:50 PM) *

I've learnt that document.getElementsByClassName() doesn't return an array but a nodelist

In my understanding, a node list is a kind of array. unsure.gif

QUOTE
<script type="text/javascript">
<!--

Sidenote: the SGML comments have not been needed for the last 15-20 years or so. The TYPE attribute is required by HTML4, but in HTML5 you can skip that too.

QUOTE
idiots.item(i).style.color = 'red';

You can use the above or just

CODE
idiots[i].style.color = 'red';

I don't know of any practical difference (I always use the shortest, of course).

What makes the script fail is that you forgot one closing curly bracket after the loop. Also, document.onload is not correct AFAIK. These should work:

CODE
document.body.onload = blah;

window.onload = blah;

but I don't recommend them either, since you can only use them once on a page. It's much better to use addEventListener, since you can use several of them on the same page. Here are two examples:

CODE
window.addEventListener('DOMContentLoaded', blah, false);

window.addEventListener('load', blah, false);

(not sure if the false flag is still needed?).

DOMContentLoaded fires when only the HTML code has loaded, while load fires when HTML and external files (images, CSS and JS) have loaded.
pandy
QUOTE(Christian J @ Sep 6 2020, 11:46 PM) *

In my understanding, a node list is a kind of array. unsure.gif


Linguistically maybe, but it can't be treated as a normal array in JS from what I understand.


QUOTE
Sidenote: the SGML comments have not been needed for the last 15-20 years or so. The TYPE attribute is required by HTML4, but in HTML5 you can skip that too.


I know that, believe it or not. It's the only way to make my editor use some kind of syntax highlighting. I didn't think I'd needed to clean it up for display. biggrin.gif

QUOTE
QUOTE
idiots.item(i).style.color = 'red';

You can use the above or just

CODE
idiots[i].style.color = 'red';

I don't know of any practical difference (I always use the shortest, of course).

But I can't! The normal for loop was where I started.

QUOTE
What makes the script fail is that you forgot one closing curly bracket after the loop. Also, document.onload is not correct AFAIK. These should work:


Oops! Copying error. It's there. Do you mean it actually runs for you with the closing brace there? Did you try it? blink.gif

QUOTE
]Also, document.onload is not correct AFAIK


It seems it is kosher again. Supposedly window and document onload fire at different points of loading.

And... that was it after all. Changing to window.onload made the trick. What a read about firing at different points made me think document.onload would be better. Maybe I confused things.

The below, where it all started, does not run though. But that's according to what the sites I read says, so that's fine.
CODE
idiots.[i],style.color = 'red';


Thanks. I'll get back to the read real thing and see if it works there too.
Christian J
QUOTE(pandy @ Sep 6 2020, 11:59 PM) *

Did you try it? blink.gif

Of course:

CODE
function blah()
{
    var idiots = document.getElementsByClassName("dumb");
    for (var i = 0; i < idiots.length; i++)
    {
        idiots[i].style.color = 'red';
    }
}
window.addEventListener('DOMContentLoaded', blah, false);


QUOTE
Supposedly window and document onload fire at different points of loading.

Now I found something like that on Stackoverflow, but it doesn't work in my browsers. unsure.gif An inline event like

CODE
<body onload="blah()">

does work of course.

QUOTE
CODE
idiots.[i],style.color = 'red';

That should be

CODE
idiots[i].style.color = 'red';
CharlesEF
I'm not sure document.onload works or not. But, if it does you still placed the command before the HTML was rendered. So, idiots will always be empty.
Christian J
QUOTE(CharlesEF @ Sep 7 2020, 12:34 AM) *

if it does you still placed the command before the HTML was rendered. So, idiots will always be empty.

That would be correct with something like:

CODE
<script type="text/javascript">
function blah()
{
    var idiots = document.getElementsByClassName("dumb");
    for (var i = 0; i < idiots.length; i++)
    {
        idiots[i].style.color = 'red';
    }
}
blah(); // no onload is used!
</script>

But the very purpose of the onload event if to create a delay until the page is loaded, that's why my example in my previous post works.



CharlesEF
Yes, that's true. That's what I get for posting too soon after getting up. dry.gif
pandy
QUOTE(Christian J @ Sep 7 2020, 01:51 AM) *

But the very purpose of the onload event if to create a delay until the page is loaded, that's why my example in my previous post works.


No, I also had onload. I think yours work because you used addEventListener and not onclick as I did. Because mine doesn't work with idiots[i].style.color = 'red';.

Anyhow, I got what I was doing to work after much brooding. It was easier once this was solved. And I learnt few new things I need to read up about. Like 'item' and 'event' used like so: onclick="aFunction(event)". I don't like using things I'm not familiar with. blush.gif
Christian J
QUOTE(pandy @ Sep 7 2020, 03:37 AM) *

No, I also had onload.

That was document.onload, which doesn't work. document.body.onload or window.onload work, though:

CODE
function blah()
{
    var idiots = document.getElementsByClassName("dumb");
    for (var i = 0; i < idiots.length; i++)
    {
        idiots[i].style.color = 'red';
    }
}
document.body.onload=blah;

(BTW you don't have to put the JS in the HEAD section).

QUOTE
onclick="aFunction(event)". I don't like using things I'm not familiar with. blush.gif

I don't understand things like "event" or "e" very well either, and tutorials I've found rarely make much sense.

pandy
QUOTE(Christian J @ Sep 7 2020, 02:37 PM) *

That was document.onload, which doesn't work. document.body.onload or window.onload work, though:

I changed that as you may recall.

QUOTE

I don't understand things like "event" or "e" very well either, and tutorials I've found rarely make much sense.


Hadn't even heard about them before.
Christian J
QUOTE(pandy @ Sep 7 2020, 03:31 PM) *

I changed that as you may recall.

Yes but then you introduced these typos:

CODE
idiots.[i],style.color = 'red';

smile.gif

QUOTE
Hadn't even heard about them before.

https://quirksmode.org/js/introevents.html and http://quirksmode.org/js/events_access.html mention it (though much of the content deals with older browser, that are not an issue anymore). Please let us know if you find some better tutorials.

This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2024 Invision Power Services, Inc.