AWRDev.
AWRDev.

Reputation: 45

Getting an element HTML

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

Answers (4)

M.A.S
M.A.S

Reputation: 343

You can try :

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

Upvotes: 4

FZs
FZs

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

Mamun
Mamun

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

Manav Akela
Manav Akela

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

Related Questions