menteith menteith - 1 month ago 6
Javascript Question

Targeting specific class when there are more than one element with the same class?

I'd like to get the content of a specific class but more than one class with the same name. Let's take as an example class

box_nag
. I can the first class of that name by:

document.getElementsbyClassName("box_nag")[0].textContent


And the second class by:

document.getElementsbyClassName("box_nag")[1].textContent


However, I think it would be better to take into account also numbers, in this example
1
and
2
:

h1 class="box_nag"

h2 class="box_nag"

How do I do that in JavaScript?

<h1 class="box_nag"><a href="/wydanie/0,20119.html">
Polityka - nr 44 (3083) z dnia 2016-10-26; s. 15-18</a></h1>
<h2 class="box_nag"><a href="/dzial/polityka,0,356.html">Polityka</a></h2>

Answer

Use document.querySelector() or document.querySelectorAll() and combine the class name with the tag name (fiddle in case the service is down):

document.querySelector('h1.box_nag').style.color = 'red';

document.querySelector('h2.box_nag').style.color = 'green';
<h1 class="box_nag">H1</h1>

<h2 class="box_nag">H2</h2>

Comments