Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 968
Fábio Pavani Avatar asked Jan 13 '23 07:01

Fábio Pavani


2 Answers

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.

like image 82
Denys Séguret Avatar answered Jan 20 '23 20:01

Denys Séguret


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

like image 42
scrblnrd3 Avatar answered Jan 20 '23 22:01

scrblnrd3