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

Fábio Pavani picture Fábio Pavani · May 24, 2013 · Viewed 16k times · Source

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?

Answer

Denys S&#233;guret picture Denys Séguret · May 24, 2013

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.