treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Javascript: Selecting an elment with a class within an element with an id

  • I've tried the following but that didn't work. No jQuery.
    document.getElementById('theId').getElementsByClassName('theClass');


    Turns out this WAS selecting it properly. Something else in my code was broken
  • You'll have to use an index number, to indicate which one of the found elements with that class you want to target. This will select the first one:

    document.getElementById('theId').getElementsByClassName('theClass')[0];
    I've never figured out how to select all classes with getElementsByClassName, so that's why jQuery is so great.
  • Note: getElementsByClassName doesn't have great browser support
  • What I use instead is the tag name, because in most cases (at least for me) the tags for the class are all the same:


    var tags = getElementsByTagName('a');
    for(i=0;i<tags.length;i++){
    if(tags[i].className==='theClassWanted') {
    //code to execute
    }
    }