menteith menteith - 1 year ago 64
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

. I can the first class of that name by:


And the second class by:


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

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 Source

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download