[英]Add class inside another element via javascript?
I want to add a class to a class to a specific element, that is in another element via javascript.我想将 class 添加到 class 到特定元素,即通过 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”的 div 我在这样的 a-tag 中有一个链接图像
<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:现在我需要将 class 添加到超链接元素中,例如:
<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.有没有错误。
It works: https://stackblitz.com/edit/js-jquery-find-in-a-doc-addclass?file=index.html它有效: https://stackblitz.com/edit/js-jquery-find-in-a-doc-addclass?file=index.html
You used it in a doc ready function, like this?您在准备好的文档 function 中使用它,像这样?
$(document).ready(function(){
jQuery('div.jet-woo-product-thumbnail').find('a').addClass('my_class');
});
Make sure you've closed the div tag correctly.确保您已正确关闭 div 标签。 In your example code it is not closed:在您的示例代码中,它没有关闭:
<div class="jet-woo-product-thumbnail">
...
</div>
Otherwise jquery will not work.否则 jquery 将无法工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.