How can i get elements by class instead of "GetElementById"?

16,076

Solution 1

The precise name is important.

Change

getElementByClassName

to

getElementsByClassName

There's a s because there might be more than one element with a give class, contrary to elements with a specific id.

Solution 2

There can be many elements with the exact same class names, so you have to adjust it for that

instead of

getElementByClassName

you have to do

getElementsbyClassName("someclass");

and it will return an array of all of them

Share:
16,076
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    Admin about 2 years

    So, this is the code:

    <a id="link" href="https://url.com/">URL:</a>
    <input id="value"/>
    
    <script type="text/javascript">
        var link= document.getElementById('link');
        var input= document.getElementById('value');
        input.onchange=input.onkeyup= function() {
            link.search= 'extendurl/'+encodeURIComponent(input.value);
        };
    </script>
    

    this is working, but i need to use the class instead of the ID. I try this:

    <script type="text/javascript">
        var link= document.getElementByClassName("link")[0];
        var input= document.getElementByClassName("value")[0];
        input.onchange=input.onkeyup= function() {
            link.search= 'extendurl/'+encodeURIComponent(input.value);
            link.firstChild.data= link.href;
        };
    </script>
    
    <a class="link" href="https://url.com/">URL:</a>
    <input class="value"/>
    

    i don't know why, but this isn't working.

    Someone?

  • Rob W
    Rob W about 11 years
    Don't forget to cast a close vote.
  • Denys Séguret
    Denys Séguret about 11 years
    @RobW done. I'm amazed you find a duplicate for this one...
  • Rob W
    Rob W about 11 years
    @dystroy This is a common typo, I just Googled for it: site:stackoverflow.com getElementByClassName, and found this as the third result.