0

Basically I have three small div sections with the same class name(box) and I want to select the second one so I can select another p-Tag etc.

So far this is what I tried :

var select = document.querySelectorAll('.clearfix box box');

Of course, how this is written is wrong and I have no other ideas.

Html :

<div class="box">
  <p>Nulla consequat massa quis enim. Donec pede justo,fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus
    ut, imperdiet a, venenatis vitae, justo.</p>
</div>

<div class="box">
  <p>Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus
    ut, imperdiet a, venenatis vitae, justo.</p>
</div>

<div class="box">
  <p>Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus
    ut, imperdiet a, venenatis vitae, justo.</p>
</div>
  • 2
    Could you add the html to the question please – Get Off My Lawn Jul 21 '18 at 17:06
  • 1
    Possible duplicate of [How to get the second match with QuerySelector?](https://stackoverflow.com/questions/22902447/how-to-get-the-second-match-with-queryselector) – Heretic Monkey Jul 21 '18 at 17:17
  • Thanks for the answers everyone, however now I should replace the value of the p-Tag with some other text, how do I do that?! –  Jul 21 '18 at 17:29

3 Answers3

2

You need to select the elements by using the class selector and then get the second one from the selected elements:

document.querySelectorAll('.clearfix .box')[1];

Here, the document.querySelectorAll will return the divs with class box and then [1] will get the second one.

31piy
  • 23,323
  • 6
  • 47
  • 67
  • Thanks for the answer, I added my HTML in there take a look, basically .clearfix is the parent of both of those divs so thats what I tried there. Btw I dont understand what you mean, should I treat class as an attribute you mean?! –  Jul 21 '18 at 17:12
1

With your html is setup like this, you can use the selector

.clearfix .box:nth-child(2)

This will get the second div in clearfix with a class containing box

let select = document.querySelector('.clearfix .box:nth-child(2)')
let p = document.createElement('p')
p.textContent = 'New p element'
select.appendChild(p)
<div class="clearfix">
  <div class="box"><p>I am div 1</p></div>
  <div class="box"><p>I am div 2</p></div>
</div>
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
0

What if you tried this:

var select = document.getElementsByClassName("box")[1]

getElementsByClassName selects all classes named box in the document

[1] selects the second object (the index for the first object is 0)

Matthijs Knigge
  • 402
  • 2
  • 10