简体   繁体   English

通过 javascript 在另一个元素中添加 class?

[英]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.

相关问题 如何将类添加到 Html 或 Javascript 中的元素? - How to add class to an element in Html or via Javascript? 如果元素通过javascript具有特定文本,则向元素添加css类 - Add a css class to an element if the element has a certain text via javascript 在Javascript中的另一个元素内修改元素的类 - Modify an element's class inside another element in Javascript 在 JavaScript 类选择的另一个元素中选择一个标签元素 - Select a tag element inside a another element selected by class JavaScript 如果另一个元素具有活动 class,则添加 class,如果没有 javascript / Z6A2D7208853DAFFCB96FB5A7382B0C7,则将其删除 - Add class if another element has active class and delete this if not with javascript / JQuery 通过javascript / jquery将class / id添加到带有特定文本的div中 - add class/id via javascript/jquery to div with specific text inside 使用javascript将类添加到元素 - Add a class to an element with javascript 通过JavaScript将元素固定到另一个元素的底部 - Pin element to bottom of another element via JavaScript 如何通过Angular将鼠标悬停在另一个元素上时添加和删除一个元素的类? - How to add and remove class of one element while hovering over another element via Angular? 如果元素具有类,则将类添加到另一个元素 - If element has class add class to another element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM