0

I have the following code generated by Simple Html Dom Parser:

<a href='....'>
   <div class='test'>...</div>
</a>

How can I add a class to the a element? I presume that I can do this with Jquery?

I only need to add a class to the elements that have a div with class 'test' as descendant.

stijn.aerts
  • 5,724
  • 5
  • 28
  • 43

4 Answers4

4

Either

$('.test').parent().addClass('whatever');

Or

 $('.test').closest('a').addClass('whatever');

The first if you know the a element is the parent, the second if you just know the a element contains, even multiple levels deep, the .test class

dave
  • 57,127
  • 4
  • 69
  • 87
1

You can use the parent method:

$('.test').parent().addClass('my-class');

Or without jQuery:

/* On one element. */
document.querySelector('.test').parentNode.classList.add('my-class') ;
/* On all elements. */
[].forEach.call(document.querySelectorAll('.test'), function (div) {
    div.parentNode.classList.add('my-class');
});
Holt
  • 34,843
  • 7
  • 82
  • 128
0

In vanilla JS, also considering that .test can be a further descendant than a child:

[].forEach.call(document.getElementsByTagName('a'), function(node) {
    if ( node.querySelector('.test') )
        node.classList.add('foo')
})
David Hellsing
  • 102,045
  • 43
  • 170
  • 208
0

To add class
$('.test').parent().addClass('yourClass');

To remove class
$('.test').parent().removeClass('yourClass');