简体   繁体   中英

Display <textarea> content in <div>

I'm really new to Javascript. I am trying to output the current date and also the content in the textarea tag in HTML on button click.
However I do not know how to obtain the content when the textarea is not declared along with a name/id/class.

Here's my code:

<script>
   function displayPost() {
      var thisDiv = document.getElementById("posts");
      var date = new Date();
      date.classList.add("post-time");
      var textarea = document.getElementByTagName("textarea");
      textarea.classList.add("post-content");
      thisDiv.innerHTML = date + textarea;
   }
</script>


<html>
  <div id="posts"></div>
  <textarea rows="4" cols="60">Type your text here...</textarea>
  <button onclick = "displayPost()">Post</button>
</html>

Any sort of help is appreciated! Thank you in advance!

You can use document.querySelector when a dom element does have any name/id/class like:

var textarea = document.querySelector('textarea');

To get the current date in a readable format, you can use toLocaleString() method:

var date = new Date();
console.log(date.toLocaleString());
// → "3/21/2020, 7:00:00 PM"

To get <textarea> current entered value you can use:

var textarea = document.querySelector('textarea');
console.log(textarea.value);

DEMO:

 function displayPost() { var thisDiv = document.getElementById('posts'); var date = new Date(); thisDiv.classList.add("post-time"); var textarea = document.querySelector('textarea'); textarea.classList.add("post-content"); thisDiv.innerHTML = date.toLocaleString() + ': '+ textarea.value; }
 .post-time{padding:20px 0}
 <div id="posts"></div> <textarea rows="4" cols="60" placeholder="Type your text here..."></textarea> <button onclick="displayPost()">Post</button>

you can make use of document.querySelector() which returns first matching element or document.getElementsByTagName() which returns NodeList of all the textarea elements

var textarea = document.querySelector('textarea').value;

or

var textarea = document.getElementsByTagName('textarea')[0].value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM