简体   繁体   English

获取元素HTML

[英]Getting an element HTML

I have HTML document like this 我有这样的HTML文档

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

I can access first div element via getElementById but can I access somehow Second element? 我可以通过getElementById访问第一个div元素,但是我可以以某种方式访问​​第二个元素吗?

You can use Document.querySelectorAll() with specific index like the following way: 您可以将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") returns all divs into a HTMLCollection object, the first div is 0 second div is 1 : 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> 

Method 1: get Parent Element then count to your desired element then read by it name, 方法1:获取父元素,然后计算到所需元素,然后按其名称读取,

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

Method 2: direct count to div like mentioned but in some cases it won't works 方法2:直接计数到div就像提到的那样,但在某些情况下将不起作用

document.getElementByTagName("div")[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM