首页 > 解决方案 > 获取没有 ID 的文本区域的值 - Vanilla JS

问题描述

我正在尝试获取没有 id 的 html 的值。

代码 -

<section class="post">
  <textarea rows="5" placeholder="(New Post)"></textarea>
</section>

JS 我试过::

var entryText = document.textarea.value;
var entryText = document.getElementsByTagName.value;

标签: javascript

解决方案


document.querySelector()您可以为此任务使用更现代的方法来选择textarea位于section具有类的块中的第一个post

var entryText = document.querySelector("section.post textarea").value;
console.log(entryText);
<section class="post">
  <textarea rows="5" placeholder="(New Post)">This is some default text, to show that the call to console.log() works.</textarea>
</section>

您可能希望进一步深入了解CSS 选择器的文档,这是document.querySelector()'s 参数所需要的。


推荐阅读