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
  • 6,026
  • 5
  • 30
  • 46

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
  • 62,300
  • 5
  • 72
  • 93
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
  • 36,600
  • 7
  • 92
  • 139
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
  • 106,495
  • 44
  • 176
  • 212
0

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

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