Jaeger
Jaeger

Reputation: 51

Change the class of the preceding element

Here's the structure of my code. I need to change the class of the h3 tag before a div in jquery, for example I need to change the class of the h3 class above the div with an ID of "firstCol".


‹h3 class="class123"› ‹a href="#"› First Column ‹/a›  ‹/h3 ›

‹div id="firstCol" class="myStyle"› Content Here ‹/div ›

‹h3 class="class123">‹a href="#"›First Column‹/h3›

‹div id="secondCol" class="myStyle"›Content Here‹/div›

Can someone help me please..

Upvotes: 0

Views: 55

Answers (3)

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

This will change the class of the element before the div...

$('#firstCol').prev().attr("class", "new-class");

There are ways to remove, add and toggle classes, but that will remove all classes and add a new one.

Upvotes: 0

Igor
Igor

Reputation: 33983

There's no single function to change a class, but you can remove the previous one and add your new one:

$('#firstCol').prev('h3').removeClass().addClass('newClass');

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68400

Maybe this?

$('#firstCol').prev().addClass('yourClass');

Upvotes: 2

Related Questions