gpt4 book ai didi

javascript - jquery如果元素包含文本,将类添加到父div

转载 作者:可可西里 更新时间:2023-11-01 02:18:09 25 4
gpt4 key购买 nike

如果其中一个子元素包含单词“Sponsored”,我需要向父 div 添加一个类。

<div id="post-item">   
<span class="tags">
<a href="#">Blogs</a>
</span>
</div>

<div id="post-item">
<span class="tags">
<a href="#">Sponsored by Lorem Ipsum</a>
</span>
</div>

我目前正在尝试使用 parent().addClass 但由于某种原因它无法正常工作。你可以在这个 fiddle 中看到一个例子:http://jsfiddle.net/VrPdF/

if (jQuery('a:contains("Sponsored")').length) {
jQuery(this).parent('#post-item').addClass('sponz');

}

我们将不胜感激 - 谢谢!

最佳答案

ID 必须是唯一的,因此使用类来标识父级。您可以使用 .closest() 来识别具有类 post-item 的父级。

HTML

<div class="post-item">   
<span class="tags">
<a href="#">Blogs</a>
<h3>Lorem</h3>
</span>
</div>

<div class="post-item">
<span class="tags">
<a href="#">Sponsored by Lorem Ipsum</a>
</span>
<h3>Lorem</h3>
</div>

JavaScript

jQuery('a:contains("Sponsored")').closest('.post-item').addClass('sponz');

DEMO


:has() Selector也可以用

Selects elements which contain at least one element that matches the specified selector.

jQuery('.post-item:has(a:contains("Sponsored"))').addClass('sponz');

jsFiddle

关于javascript - jquery如果元素包含文本,将类添加到父div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21515784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com