4

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?

Fábio Pavani
  • 73
  • 1
  • 1
  • 2
  • http://stackoverflow.com/questions/1933602/how-to-getelementbyclass-instead-of-getelementbyid-with-javascript?rq=1 – Matt Ball May 24 '13 at 16:54
  • Please read the `Questions that may already have your answer` section when posting new questions. – Esteban May 24 '13 at 17:20

2 Answers2

7

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Don't forget to cast a close vote. – Rob W May 24 '13 at 16:56
  • @RobW done. I'm amazed you find a duplicate for this one... – Denys Séguret May 24 '13 at 16:58
  • @dystroy This is a common typo, I just Googled for it: [`site:stackoverflow.com getElementByClassName`](https://encrypted.google.com/search?q=site:stackoverflow.com+getElementByClassName), and found this as the third result. – Rob W May 24 '13 at 17:00
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

scrblnrd3
  • 7,228
  • 9
  • 33
  • 64