/    Sign up×
Community /Pin to ProfileBookmark

DOM question – how to get all instances of a class?

Hi folks –

I have a bit of a dilemma with a project I’m working on and could use some help. I’m trying to change the visibility of all instances of a particular class in a page.

This is an example of what the HTML looks like:

[code]<div id=”nav1″><img src=””>
<div class=”textcolor”>here is some text</div>
</div>[/code]

The id increases by 1 from nav1 to nav6. The class “textcolor” is the one I want to affect.

The catch is this is being developed for a special browser that only supports a small subset of DOM 1 and Javascript 1.3. I’ve tried cycling through each tag using [b]allPageTags = document.getElementsByTagName(“*”)[/b] and then pulling the class out via [b]if (allPageTags[i].className==”textColor”)[/b], but it doesn’t work for this browser. ?

Can anyone recommend a way for me to accomplish this?

Thanks!

to post a comment
JavaScript

18 Comments(s)

Copy linkTweet thisAlerts:
@gil_davisAug 19.2004 — Watch out for CaPiTaLiZaTiOn.
Copy linkTweet thisAlerts:
@FangAug 19.2004 — If the DOM won't work, try [URL=http://www.alistapart.com/articles/n4switch/]Style sheet swapping[/URL]
Copy linkTweet thisAlerts:
@CharlesAug 19.2004 — There is no "document.getElementsByClassName()", perhaps because elements can belong to several different classes at once, but there is a "document.getElementsByName()". It's ugly, but you could give every element with the className of "textColor" that name.
Copy linkTweet thisAlerts:
@neilioauthorAug 19.2004 — Wow, thanks for the speedy replies, everyone! I owe you all a Coke.
[i]Originally posted by Charles [/i]

[B]There is no "document.getElementsByClassName()", perhaps because elements can belong to several different classes at once, but there is a "document.getElementsByName()". It's ugly, but you could give every element with the className of "textColor" that name. [/B][/QUOTE]

How would the syntax for that look like? I'm still learning the DOM and my assumption is that, if the items in question do not have a "name" attribute assigned, I can't access them with getElementsByName, right?

Neil
Copy linkTweet thisAlerts:
@steelersfan88Aug 19.2004 — The ugly idea as Charles mentioned would work:&lt;div class="textclr' name='textclr'&gt;foo&lt;/div&gt;and then the script:[code=php]var elems = document.getElementsByName('textclr');
for(var i=0,a;a=elems[i];i++) {
a.style.color = "forecolor";
}[/code]
Or your way should work ...:[code=php]var elems = document.getElementsByTagName('div');
for(var i=0,a;a=elems[i];i++) {
if(a.className=="textclr") {
a.style.color = "forecolor";
}
}[/code]
Dr. Script
Copy linkTweet thisAlerts:
@steelersfan88Aug 19.2004 — [i]Originally posted by neilio [/i]

[B]Wow, thanks for the speedy replies, everyone! I owe you all a Coke.



How would the syntax for that look like? I'm still learning the DOM and my assumption is that, if the items in question do not have a "name" attribute assigned, I can't access them with getElementsByName, right?



Neil [/B]
[/QUOTE]
Good ... I like Coke ?

Give all the elements a name id of the same thing, then use my first example above (what Charles referred to). You can almost bet Charles is writing a full page script for you with an example right now ...
Copy linkTweet thisAlerts:
@neilioauthorAug 19.2004 — I should note that these are the only object methods I can use (it's painful):

getElementsByName

getElementById

GetElementByID

I've been looking at this for a while. My brain hurts... ?
Copy linkTweet thisAlerts:
@steelersfan88Aug 19.2004 — This might be stretching it, but add a method (IE and Mozilla tested):[code=php]<script type="text/javascript">

document.getElementsByClassName = function(clss,tag) {
var a=document.getElementsByTagName(tag);
var obj = new Object();
for(var i=0,e,j=0;e=a[i];i++) {
if(e.className==clss) {
obj[j]=e;
j++;
}
}
return obj;
}

window.onload = function() {
var elems = document.getElementsByClassName('txts','div');
for(var i=0,a;a=elems[i];i++) {
a.style.color = "blue";
}
}

</script>

<div class="txts">Fee</div>
<div class="othr">Fie</div>
<div class="othr">Foe</div>
<div class="txts">Fum</div>[/code]
The .getElementsByClassName() method has two parameters, both required. The className (first param) and the tag name (second param). The window onload function is just an example, it can be implemented in many ways.

As Charles said above, just only let the elems belong to one class.

Also, why are you limited to those methods? And also, the link posted above uses a similar function for getElementsByClassName, which doesn't allow you to limit to tag names.

Dr. Script
Copy linkTweet thisAlerts:
@steelersfan88Aug 19.2004 — It alerts the name of the class of the second node of the tag with id of 'nav1'. It is possible to, as you show, to loop through all the nodes. One would then to need to test the class name.

... it is unclear the purpose of the parent div, nav1, in the first place, in my opinion.

The true return would be some value:[code=php]<script type="text/javascript">

onload = function() {
alert(document.getElementById('nav1').childNodes.item(1).className);
// return "abc";
}

/* alerts undefined. will alert abc if
return line is uncommented. */
alert(window.onload());

</script>[/code]
Dr. Script
Copy linkTweet thisAlerts:
@steelersfan88Aug 19.2004 — The .items(#) is not recommended. The proper use is array/collection syntax:[code=php]<script type="text/javascript">

onload = function() {
for(var i=0,a;i<document.getElementById('nav1').childNodes.length;i++) {
a=document.getElementById('nav1').childNodes[i].className;
alert("Node "+ i +" : "+ a);
}
}

</script>

<div id="nav1">
<div class="a1"> </div>
<div class="a2"> </div>
<div class="a3"> </div>
</div>[/code]
Dr. Script
Copy linkTweet thisAlerts:
@steelersfan88Aug 19.2004 — Well, sumamrizing the item() method/property, according to an undisclosed source:

document.getElementsByTagName('div').item(0) is the same as document.getElementsByTagName('div')[0].

This method is meant for other programming languages where NodeLists like those returned by getElementsByTagName are not conveniently made into arrays. You don't need item() at all in JavaScript.


... I stil ldon't udnerstand why you can only use the three methods, Neil ...

Dr. Script
Copy linkTweet thisAlerts:
@neilioauthorAug 19.2004 — I stil ldon't udnerstand why you can only use the three methods, Neil..[/QUOTE]
This script is for an embedded browser that is part of an Interactive TV set top box. Needless to say, the standards support is, well, woeful.

I tried adding the [i]name[/i] attribute to the items as you pointed out:
&lt;div id="navID1"&gt;&lt;img&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;1&lt;/div&gt;
&lt;/div&gt;


And then tried adding your code into my existing script:
<i>
</i>// hide text hints
var textDivs = document.getElementsByName('navNumTextDiv');
for (var i=0,a;a=textDivs[i];i++) {
a.style.visibility = "hidden";
}


But it still doesn't seem to be working. The frustrating thing is I've gotten this to work with no problems using other methods (e.g. getElementsByTagName("div")} but with my limited options, I'm flummoxed.

Everyone's help is really appreciated!

Neil
Copy linkTweet thisAlerts:
@neilioauthorAug 19.2004 — If my limited understand is correct, the problem with this current script is that getElementsByName returns "a list of nodes" instead of an array, correct?

If so, how would I use the information returned by getElementsByName to do what I want?
Copy linkTweet thisAlerts:
@steelersfan88Aug 19.2004 — Yes, it does not return an array (although can be accessed in array) form, in case you looking to be confirmed.

You may want to try the following:[code=php]var textDivs = document.getElementsByName('navNumTextDiv');
for (var i=0,a;i<textDivs.length;i++) {
a = textDivs[i];
a.style.visibility = "hidden";
}[/code]
Same purpose overall. You should be able to use this, as this is a correct usage of document.getElementsByName() method.

Your other hope is to get the parent div by id tag, and then loop thru its children in array form:[code=php]var textDivs = document.getElementById('nav1');
for (var i=0,a;i<textDivs.children.length;i++) {
a = textDivs[i];
a.style.visibility = "hidden";
}[/code]
That should work as well.

Dr. Script
Copy linkTweet thisAlerts:
@neilioauthorAug 19.2004 — Weird. When I try to alert back textDiv.length, I get "0". Here's an example of the exact HTML I have to work with (it's repeated 6 times, with a different top id [e.g. "navNewsDiv", "navMusicDiv", etc.]):

&lt;div id="navNewsDiv"&gt;&lt;img src="images/nav/navNews_i.gif" width="128" height="97"
border="0" id="newsImg"&gt;&lt;br /&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;1&lt;/div&gt;

Any idea why the length of textDiv.length is zero? I get the same result with my previous script, or with the new one you just posted.

Neil
Copy linkTweet thisAlerts:
@steelersfan88Aug 19.2004 — Is it 6 of the following:&lt;div id="navNewsDiv"&gt;&lt;img src="images/nav/navNews_i.gif" width="128" height="97"
border="0" id="newsImg"&gt;&lt;br /&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;1&lt;/div&gt;
&lt;/div&gt;
or the following:&lt;div id="navNewsDiv"&gt;&lt;img src="images/nav/navNews_i.gif" width="128" height="97"
border="0" id="newsImg"&gt;&lt;br /&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;1&lt;/div&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;2&lt;/div&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;3&lt;/div&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;4&lt;/div&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;5&lt;/div&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;6&lt;/div&gt;
&lt;/div&gt;
?
Copy linkTweet thisAlerts:
@neilioauthorAug 19.2004 — Sorry, I just edited my previous reply, but I'll repeat it here. There's six separate code chunks, exact identical except for a different ID at the top:

&lt;div id="navNewsDiv"&gt;&lt;img src="images/nav/navNews_i.gif" width="128" height="97"
border="0" id="newsImg"&gt;&lt;br /&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;1&lt;/div&gt;
&lt;/div&gt;
&lt;div id="navMusicDiv"&gt;&lt;img src="images/nav/navMusic_i.gif" width="128" height="97"
border="0" id="newsImg"&gt;&lt;br /&gt;
&lt;div class="navNumTextDiv" name="navNumTextDiv"&gt;2&lt;/div&gt;
&lt;/div&gt;
etc...

Unfortunately, the entire chunk isn't wrapped in an ID. I didn't write the HTML, but I might be able to get a name attribute added, which is why I've been trying to get this to work.
Copy linkTweet thisAlerts:
@steelersfan88Aug 19.2004 — Could be better ... but, how 'bout:[code=php]<script type="text/javascript">

function something(bln) {
var textDivs = document.getElementById('nav');
for (var i=0,a;i<textDivs.children.length;i++) {
a = textDivs.children[i];
if(a.nodeName == "DIV") {
a.children[2].style.visibility = bln.toProp();
}
}
}

Boolean.prototype.toProp = function() {
return (this==true) ? "hidden" : "visible";
}

</script>

<div id="nav">
<div id="nav1">
<img src="..." width="128" height="97" border="0" id="..."><br />
<div class="navNumTextDiv" name="navNumTextDiv">1</div>
</div>
<div id="nav2">
<img src="..." width="128" height="97" border="0" id="..."><br />
<div class="navNumTextDiv" name="navNumTextDiv">2</div>
</div>
<div id="nav3">
<img src="..." width="128" height="97" border="0" id="..."><br />
<div class="navNumTextDiv" name="navNumTextDiv">3</div>
</div>
<div id="nav4">
<img src="..." width="128" height="97" border="0" id="..."><br />
<div class="navNumTextDiv" name="navNumTextDiv">4</div>
</div>
<div id="nav5">
<img src="..." width="128" height="97" border="0" id="..."><br />
<div class="navNumTextDiv" name="navNumTextDiv">5</div>
</div>
<div id="nav6">
<img src="..." width="128" height="97" border="0" id="..."><br />
<div class="navNumTextDiv" name="navNumTextDiv">6</div>
</div>
<input type="checkbox" onclick="something(this.checked)" value="Do Something!">Hide/Show
</div>[/code]
(The images aren't right, and all the div names are changed for easy copy/paste. The only name that matters is the parent div.
×

Success!

Help @neilio spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...