[英]Get span value inside h1 by referring to h1 id
I want to get the text value (QCD Automotive) in this following HTML tag but can't: 我想在以下HTML标记中获取文本值(QCD Automotive),但不能:
<h1 class="_58gi" id="pages_name"><span>QCD Automotive</span><span class="_5rqt"><span class="_5rqu"></span></span></h1>
I've tried this so far, but it doesn't seem to be working. 到目前为止,我已经尝试过了,但是似乎没有用。 What am I doing wrong?
我究竟做错了什么?
pageName = document.GetElementById("pages_name").GetElementByTagName("span").innerText
它不是GetElementById
只是使用getElementById
。
You just call wrong function by case-sensitve, your statment should be like this: 您只区分大小写调用错误的函数,您的陈述应如下所示:
pageName = document.getElementById("pages_name").innerText
use getElementById()
instead of GetElementById()
and getElementByTagsName()
instead of .GetElementByTagName()
. 使用
getElementById()
代替GetElementById()
和getElementByTagsName()
代替.GetElementByTagName()
。
Notice: document.getElementByTagsName()
return array of elements, so if you want to use, you have to access via array index: result[0]
. 注意:
document.getElementByTagsName()
返回元素数组,因此,如果要使用,则必须通过数组索引: result[0]
进行访问。
In your case, just get innerText
from element H1, no need to go to insides element. 在您的情况下,只需从元素H1获取
innerText
,而无需转到insides元素。
Here is a simple solution using Jquery 这是使用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());
});
Here is a link to the working demo 这是工作演示的链接
If you want to get the first span value, use firstChild 如果要获取第一个跨度值,请使用firstChild
document.getElementById("pages_name").firstChild.span
OR 要么
use children 用孩子
document.getElementById("pages_name").children[0].innerHTML
Note: children[0] is the first element in the pages_name div. 注意: children [0]是pages_name div中的第一个元素。
(your browser's debugger should tell you that ) .getElementByTagName does not exist. (您的浏览器的调试器应该告诉您).getElementByTagName不存在。
of course .getElementsByTagName does exist : mind the 's' in Element s . 当然.getElementsByTagName确实存在:请注意Element中的 ' 。 You'll get an HTMLNodeCollection, which looks like an array but is not quite it.
您将获得一个HTMLNodeCollection,它看起来像一个数组,但不完全是一个数组。 More on MDN
有关MDN的更多信息
It has a property named length and all indices are numerical, so you can iterate over it with 它具有一个名为length的属性,并且所有索引都是数字,因此您可以使用对其进行迭代
for(i=0;i<yourcollection.length;i++)
or with the silly looking construct : 或与愚蠢的构造:
[].forEach.call(yourCollection, function(item,index){
//whatever has to be done on each item
}
And remember : MDN is your friend ! 记住:MDN是您的朋友!
尝试这个
pageName = document.getElementById("pages_name").getElementsByTagName("span")[0].innerText
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.