0

I want to add a class to a class to a specific element, that is in another element via javascript. In my case I have a div with the class "jet-woo-product-thumbnail" inside this div I have a linked image inside an a-tag like this

<div class="jet-woo-product-thumbnail">
  <a href="https://example.com" rel="bookmark">
    <img width="300" height="300" src="https://example.com/image.png" class="attachment-woocommerce_thumbnail size-woocommerce_thumbnail" alt="">
  </a>

Now i need to add the class to the hyperlink element like:

<div class="jet-woo-product-thumbnail">
  <a href="https://example.com" class="my_class" rel="bookmark">
    <img width="300" height="300" src="https://example.com/image.png" class="attachment-woocommerce_thumbnail size-woocommerce_thumbnail" alt=""></a>

I tried:

jQuery('div.jet-woo-product-thumbnail').find('a').addClass('my_class');

but this did not work. Is there any error.

2
  • Try $('.jet-woo-product-thumbnail a').addClass('class') Commented Jun 4, 2020 at 9:40
  • "Did not work" is not a sufficient description of the problem. Commented Jun 4, 2020 at 9:56

1 Answer 1

1

It works: https://stackblitz.com/edit/js-jquery-find-in-a-doc-addclass?file=index.html

You used it in a doc ready function, like this?

$(document).ready(function(){
  jQuery('div.jet-woo-product-thumbnail').find('a').addClass('my_class');
});

Make sure you've closed the div tag correctly. In your example code it is not closed:

<div class="jet-woo-product-thumbnail">
...
</div>

Otherwise jquery will not work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.