.getElementsByClassName wont work

Discussion in 'JavaScript' started by bdfsar, Apr 26, 2013.

  1. #1
    http://jsfiddle.net/egCqb/329/



    http://jsbin.com/emasoh/4/edit..
    ..


     
    Last edited: Apr 27, 2013
    bdfsar, Apr 26, 2013 IP
  2. bdfsar

    bdfsar Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #2
    http://jsfiddle.net/egCqb/329/


    http://jsbin.com/emasoh/4/edit
     
    Last edited: Apr 27, 2013
    bdfsar, Apr 27, 2013 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    getElementsByClassName returns a nodeList -- aka an array of elements, NOT JUST ONE ELEMENT. You need to run a for loop on that array to get EVERY element with that class. Notice that it's getElementS -- plural! This is because unlike ID's, classes can occur more than once on a page. If you are only targeting one element, it should have a unique ID, not a class!

    Also, setting innerHTML of an object to itself is pretty broken, did you mean to set it to y instead of x? This is why I don't like vague single letter names on things other than indexes.

    Oh, and you don't actually CALL newfunction in your fiddle.

    function newFunction() {
    
    	var
    		replaceValue = 'hi',
    		demoClassList = document.getElementsByClassName('demo');
    		
    	for (var t=0; t<demoClassList.length; t++) {
    		demoClassList[t].innerHTML = replaceValue;
    	}
    	
    }
    
    // actually call that function!
    newFunction();
    Code (markup):
    Be also warned older browsers still in circulation don't know getElementsByClassName, which is a reason to avoid using it or be prepared to use some sort of polyfill/shiv to provide the same functionality.

    In general though, this is why if you are going to target just one element, use a ID and getElementById -- even when supported getElementsByClassName is slow, since it has to walk the entire DOM to get matches.
     
    deathshadow, Apr 27, 2013 IP