簡體   English   中英

獲取元素HTML

[英]Getting an element HTML

我有這樣的HTML文檔

<html>
 <head></head>
  <body>
    <div id="test_id"> First element </div>
    <div> Second element </div>
  </body>
</html>

我可以通過getElementById訪問第一個div元素,但是我可以以某種方式訪問​​第二個元素嗎?

您可以將Document.querySelectorAll()特定索引一起使用,如下所示:

 var secondDiv = document.querySelectorAll('div')[1]; console.log(secondDiv); 
 <html> <head></head> <body> <div id="test_id"> First element </div> <div> Second element </div> </body> </html> 

你可以試試 :

var x = document.getElementById("test_id").nextSibling

document.getElementsByTagName("div")將所有div返回到HTMLCollection對象中,第一個div為0第二個div為1

 var second = document.getElementsByTagName("div")[1] console.log(second.innerHTML) 
 <html> <head></head> <body> <div id="test_id"> First element </div> <div> Second element </div> </body> </html> 

方法1:獲取父元素,然后計算到所需元素,然后按其名稱讀取,

document.getElementById("test_id").parentElement.getElementByTagName("div")[0].innerHTML;

方法2:直接計數到div就像提到的那樣,但在某些情況下將不起作用

document.getElementByTagName("div")[1]

暫無
暫無

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

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