irchuxy
irchuxy

Reputation: 21

Fill textarea with js

I don't understand why this doesn't function :(

<textarea class="js-compose-text compose-text txt-size--14 scroll-v scroll-styled-v scroll-styled-h scroll-alt padding-a--0" placeholder="What's happening?" style="height: 130px;"></textarea>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
  document.getElementsByClassName("js-compose-text compose-text txt-size--14 scroll-v scroll-styled-v scroll-styled-h scroll-alt padding-a--0").value = "TESTESTTEST";
}

</script>

Upvotes: 2

Views: 1650

Answers (2)

imnikhilanand
imnikhilanand

Reputation: 31

In javascript multiple textarea's or div's can have the same class name but unique ID's. When you access any element by its id then it is unique and you can call it by its Id but when you access the element by name you, you have to access every element under the same class name by index as explained below -

<textarea class="text" id="1"></textarea> //First textarea
<textarea class="text" id="2"></textarea> //Second textarea
<textarea class="text" id="3"></textarea> //Third textarea
<textarea class="text" id="4"></textarea> //Fourth textarea

To access 3 rd text area -

document.getElementById("3");
//OR
document.getElementsByClassName("text")[2];

Both the code will do the same thing

Upvotes: 2

j08691
j08691

Reputation: 207923

getElementsByClassName returns an array-like object so you need to specify the exact element like document.getElementsByClassName("js-compose-text compose-text txt-size--14 scroll-v scroll-styled-v scroll-styled-h scroll-alt padding-a--0")[0].value = "TESTESTTEST";

<textarea class="js-compose-text compose-text txt-size--14 scroll-v scroll-styled-v scroll-styled-h scroll-alt padding-a--0" placeholder="What's happening?" style="height: 130px;"></textarea>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
  document.getElementsByClassName("js-compose-text compose-text txt-size--14 scroll-v scroll-styled-v scroll-styled-h scroll-alt padding-a--0")[0].value = "TESTESTTEST";
}

</script>

Upvotes: 3

Related Questions