how to use "getElementsByClassName"?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pano pano
    New Member
    • Nov 2011
    • 18

    how to use "getElementsByClassName"?

    Hi
    i try to apply a fade in effect

    Code:
    var fadeEffect=function(){
    	return{
    		init:function(id, flag, target){
    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
    "getElementsByC lassName" to make it work and how?
    (because obviously the getElementById doesn't work for multiple tags)
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    no you can’t do it that simple. while getElementById( ) returns an HTML Element, getElementsByCl assName() (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.

    Comment

    • Sherin
      New Member
      • Jan 2020
      • 77

      #3
      No worries if you don’t have jQuery included because we can use a function that is similar to the getElementsByCl ass: getElementsByCl assName .

      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:

      Code:
      <div class="testClass">
      	A div with class="testClass".
      </div>
      <div class="testClass">
      	The second div with the same class name.
      </div>
      <p class="testClass">
      	A paragraph with testClass
      </p>
      
      <button onclick="testFunction();">Alert the content of the first testClass</button>
      
      <script>
      function testFunction() {
          var x = document.getElementsByClassName("testClass");
          alert(x[0].innerHTML);
      }
      </script>

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5388

        #4
        No worries if you don’t have jQuery included because we can use a function that is similar to the getElementsByCl ass: getElementsByCl assName .
        this is trivial and was not the question in the original post. i suggest to read the real questions first before posting random answers.

        Comment

        Working...