user3820288
user3820288

Reputation: 225

How to get value of a text area using Java Script?

I want to fetch the text(Againnnn ??) from below html code.

<pre class="mentions-highlighter" role="presentation">Againnnn ??</pre>
<textarea class="mentions-input trans" placeholder="Add a comment..." style="height: 47px;" dir="ltr"></textarea>

I tried this but it didn't worked properly.

var comment = document.getElementsByClassName('.mentions-input trans').value;

Upvotes: 0

Views: 1736

Answers (4)

user663031
user663031

Reputation:

getElementsByClassName returns a list of elements, not a single one. Just do

var comment = document.getElementsByClassName('mentions-input trans')[0].value

(Note the [0].)

Upvotes: 0

Kurenai Kunai
Kurenai Kunai

Reputation: 1902

You can use document.getElementsByClassName with [0] to access the tag and then innerHTML to get the text value as in :

function myFunction() {
    var comment= document.getElementsByClassName("mentions-highlighter")[0].innerHTML;
    alert(comment);
}

This function will alert

"Againnnn ??"

Upvotes: 1

tutankhamun
tutankhamun

Reputation: 920

You have two mistakes in var comment = document.getElementsByClassName('.mentions-input trans').value;

  1. As @torazaburo says getElementsByClassName method returns list of elements and you may get any element by index
  2. getElementsByClassName method gets classname argument, not a selector

Worked example:

var comment = document.getElementsByClassName('mentions-input trans')[0].value;
alert(comment);
<pre class="mentions-highlighter" role="presentation">Againnnn ??</pre>
<textarea class="mentions-input trans" placeholder="Add a comment..." style="height: 47px;" dir="ltr">test value</textarea>

Upvotes: 0

Haresh Shyara
Haresh Shyara

Reputation: 1886

You can use simple text() method to get text from one class to another class. try to this script

<script>
  $(document).ready(function(){
      $('.mentions-input').text($('.mentions-highlighter').text());
  });
</script>

<pre class="mentions-highlighter" role="presentation">Againnnn ??</pre>
<textarea class="mentions-input trans" placeholder="Add a comment..." style="height: 47px;" dir="ltr"></textarea>

Upvotes: 0

Related Questions