By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,470 Members | 994 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,470 IT Pros & Developers. It's quick & easy.

how to use "getElementsByClassName"?

P: 18
Hi
i try to apply a fade in effect

Expand|Select|Wrap|Line Numbers
  1. var fadeEffect=function(){
  2.     return{
  3.         init:function(id, flag, target){
  4. this.elem = document.getElementById(id);
Right now, the effect applies to a div but i want to make it apply to multiple divs.Can i replace the "getElementById"
with
"getElementsByClassName" to make it work and how?
(because obviously the getElementById doesn't work for multiple tags)
Oct 1 '12 #1

✓ answered by Dormilich

no you canít do it that simple. while getElementById() returns an HTML Element, getElementsByClassName() (like all other getElementsBy*() functions) returns a HTMLCollection (a kind of array).
you would have to loop through all elements of that collection and apply the effect individually.

Share this Question
Share on Google+
3 Replies


Dormilich
Expert Mod 5K+
P: 8,639
no you canít do it that simple. while getElementById() returns an HTML Element, getElementsByClassName() (like all other getElementsBy*() functions) returns a HTMLCollection (a kind of array).
you would have to loop through all elements of that collection and apply the effect individually.
Oct 1 '12 #2

P: 6
No worries if you donít have jQuery included because we can use a function that is similar to the getElementsByClass: getElementsByClassName .

This pure JS method returns an array of all elements in the document with the specified class name, as a NodeList object. Try it in this JSFiddle.

Hereís the code and how to use it:

Expand|Select|Wrap|Line Numbers
  1. <div class="testClass">
  2.     A div with class="testClass".
  3. </div>
  4. <div class="testClass">
  5.     The second div with the same class name.
  6. </div>
  7. <p class="testClass">
  8.     A paragraph with testClass
  9. </p>
  10.  
  11. <button onclick="testFunction();">Alert the content of the first testClass</button>
  12.  
  13. <script>
  14. function testFunction() {
  15.     var x = document.getElementsByClassName("testClass");
  16.     alert(x[0].innerHTML);
  17. }
  18. </script>
1 Week Ago #3

gits
Expert Mod 5K+
P: 5,387
No worries if you donít have jQuery included because we can use a function that is similar to the getElementsByClass: getElementsByClassName .
this is trivial and was not the question in the original post. i suggest to read the real questions first before posting random answers.
1 Week Ago #4

Post your reply

Sign in to post your reply or Sign up for a free account.