按类名javascript获取内容

时间:2017-06-03 05:14:35

标签: javascript

我试图通过类名获取内容,但是当我运行脚本时我得到了未定义...我做错了什么?

    <!DOCTYPE html>
<html>
<body>

<td class="a-size-base">B000FNFSPY</td>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {

var x = document.getElementsByClassName("a-size-base").innerText;
    document.write(x)
}
</script>

</body>
</html>

4 个答案:

答案 0 :(得分:1)

以下是解决方案:

<!DOCTYPE html>
<html>
  <body>
   <div class="a-size-base">B000FNFSPY</div>
   <button onclick="myFunction()">Try it</button>
 <script>
   function myFunction() {
    var x = document.getElementsByClassName("a-size-base")[0].innerText;
    document.write(x)
   }
 </script>
 </body>
</html>

当浏览器使用td进行编译时,由于未使用table标记,因此它会按原样呈现,并省略td标记。

答案 1 :(得分:0)

您滥用<td>标记,必须将其放入表格中。 或者它不会使用webkit或大多数浏览器呈现到DOM中。

在Chrome中测试过。请注意,<td>不存在。

getElementsByTagName返回一个数组。但是你在第一步出错了,所以它还没有到达这里。

enter image description here

function myFunction() {
    var x = document.getElementsByClassName("a-size-base");
    document.write(x);
}
    <!DOCTYPE html>
<html>
<body>

<td class="a-size-base">B000FNFSPY</td>

<button onclick="myFunction()">Try it</button>

</body>
</html>

答案 2 :(得分:0)

你可以这样做:

<!DOCTYPE html>
<html>
<body>

<div class="a-size-base">B000FNFSPY</div>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {

var x = document.getElementsByClassName("a-size-base");
    document.write(x[0].innerHTML)
}
</script>

</body>
</html>

答案 3 :(得分:0)

getElementsByClassName方法返回一个类似数组的元素集合。您应该遍历项目以访问其innerText。

相关问题