Reputation: 45
I have HTML document like this
<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?
Upvotes: 0
Views: 98
Reputation: 18619
document.getElementsByTagName("div")
returns all divs into a HTMLCollection object, the first div is 0
second div is 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>
Upvotes: 0
Reputation: 68933
You can use Document.querySelectorAll()
with specific index like the following way:
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>
Upvotes: 5
Reputation: 174
Method 1: get Parent Element then count to your desired element then read by it name,
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
document.getElementByTagName("div")[1]
Upvotes: 0