簡體   English   中英

通過引用h1 id獲取h1內的跨度值

[英]Get span value inside h1 by referring to h1 id

我想在以下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

它不是GetElementById只是使用getElementById

您只區分大小寫調用錯誤的函數,您的陳述應如下所示:

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

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

注意: document.getElementByTagsName()返回元素數組,因此,如果要使用,則必須通過數組索引: result[0]進行訪問。

在您的情況下,只需從元素H1獲取innerText ,而無需轉到insides元素。

這是使用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());
});

這是工作演示的鏈接

如果要獲取第一個跨度值,請使用firstChild

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

要么

用孩子

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

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

(您的瀏覽器的調試器應該告訴您).getElementByTagName不存在。

當然.getElementsByTagName確實存在:請注意Element中 ' 您將獲得一個HTMLNodeCollection,它看起來像一個數組,但不完全是一個數組。 有關MDN的更多信息

它具有一個名為length的屬性,並且所有索引都是數字,因此您可以使用對其進行迭代

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

或與愚蠢的構造:

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

記住:MDN是您的朋友!

嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM