如何获得<a> innerText based on class name?

时间:2017-11-08 08:49:10

标签: javascript

Say I have: <a class="helloh" id="helloh">return this value</a>

Basically I want to get the innerText of <a> tag based on class name.

The problem is when I try: alert(document.getElementsByClassName("helloh").innerText); it return undefined but when I try: alert(document.getElementById("helloh").innerText); it return me they actual value that I want.

3 个答案:

答案 0 :(得分:3)

使用document.getElementsByClassName("helloh")[0].innerText代替document.getElementsByClassName("helloh").innerText。 使用getElementsByClassName时,与getElementById不同,您将获得元素数组而不是单个数组。

答案 1 :(得分:0)

新的语法版本是document.querySelector(),它将返回第一个匹配元素。它可以帮助您节省getElementsByClassName('name')[0]

以下内容:

<a class="helloh" id="helloh">get by ID</a>

<a class="helloh2" id="helloh2">get by Class</a>

您可以使用:

// by ID
console.log(document.querySelector('#helloh').innerText)

// by Class
console.log(document.querySelector('.helloh2').innerText)

如果您想要多个元素,可以使用document.querySelectorAll()

<a class="helloh" id="helloh">get by ID</a>

<a class="helloh" id="helloh2">get by Class</a>

// get both by Class
console.log(document.querySelectorAll('.helloh'))

请注意#.

您使用.指定了类,#指定了ID,并省略了按块元素搜索的内容。

例如,document.querySelectorAll('div')将返回页面上的所有div。

您也可以同时使用多个:

document.querySelectorAll('div .helloh #helloh2')

答案 2 :(得分:0)

&#13;
&#13;
var a = document.getElementsByClassName("helloh")[0].textContent;
alert(a);
&#13;
<a class="helloh" id="helloh">return this value</a>
&#13;
&#13;
&#13;

相关问题