通过引用h1 id获取h1内的span值

时间:2016-03-29 07:06:07

标签: javascript

我希望在以下HTML标记中获取文本值(QCD Automotive),但不能:

<h1 class="_58gi" id="pages_name"><span>QCD Automotive</span><span class="_5rqt"><span class="_5rqu"></span></span></h1>

到目前为止我已经尝试过了,但它似乎没有起作用。我做错了什么?

pageName = document.GetElementById("pages_name").GetElementByTagName("span").innerText

6 个答案:

答案 0 :(得分:3)

它不是*SIGNAL* B2B_12V CNB2.88 TC1.1 U2.1 U24.2 *SIGNAL* DDR3_VREF1 C24.1 U24.2 U24.H1 U5.6 只使用GetElementById

答案 1 :(得分:3)

你只是通过案例敏感来调用错误的功能,你的陈述应该是这样的:

pageName = document.getElementById("pages_name").innerText

使用getElementById()代替GetElementById()getElementByTagsName()代替.GetElementByTagName()

注意: document.getElementByTagsName()返回元素数组,因此如果要使用,则必须通过数组索引访问:result[0]

在您的情况下,只需从元素H1获取innerText,无需转到内部元素。

答案 2 :(得分:2)

这是一个使用Jquery

的简单解决方案
$(document).ready(function(){
  //For everything in the first span, use the code below
  alert($("#pages_name").first().text());
  //If you want every text in the tag, use the code below
  alert($("#pages_name").text());
});

以下是working demo

的链接

答案 3 :(得分:1)

如果您想获得第一个跨度值,请使用firstChild

document.getElementById("pages_name").firstChild.span

OR

使用儿童

document.getElementById("pages_name").children[0].innerHTML

注意: children [0]是pages_name div中的第一个元素。

答案 4 :(得分:1)

(您的浏览器的调试器应该告诉您).getElementByTagName不存在。

当然     .getElementsByTagName 确实存在:请注意元素 s 中的 &#39; 。您将获得一个HTMLNodeCollection,它看起来像一个数组,但并不完整。 More on MDN

它有一个名为length的属性,所有索引都是数字,所以你可以用

迭代它
for(i=0;i<yourcollection.length;i++)

或与愚蠢的构造:

[].forEach.call(yourCollection, function(item,index){
    //whatever has to be done on each item
}

请记住:MDN是你的朋友!

答案 5 :(得分:1)

试试这个

pageName = document.getElementById("pages_name").getElementsByTagName("span")[0].innerText