找到锚点并将类添加到最近的类

时间:2016-08-16 15:36:57

标签: jquery

某些DIV将具有名为outage的锚名称,并且那些应该将addClass outage添加到父类.modAcTitle,结果将是<div class="modAcTitle outage">This is a title.</div>我无法添加任何内容标题是独一无二的,所以这是我唯一能做的概念。

但是,我的方法非常糟糕,因为它会在每个.outage 中添加.modAcTitle,而不是在其内容中包含outage个锚点的标题。

我做错了什么?

$('a[name=outage]').parent().parent().parent().find('.modAcTitle').addClass("outage")

这是我的DIV结构和演示:https://jsfiddle.net/61za2n72/7/

<div id="ac_expand_0" class="modAc">
<div class="modAcTitle">This is a title.</div>
<div class="modAcContent" style="display: none;"><p><a name="outage"></a>This is Content and it has a unique name tag called outage</p>
</div>
<div class="modAcTitle">This is a title</div>
<div class="modAcContent" style="display: none;"><p><a name="outage"></a>This is Content and it has a unique name tag called outage</p>
</div>
<div class="modAcTitle">This is a title</div>
<div class="modAcContent" style="display: none;"><p>This is content, but it doesn't have a name tag.</p>
</div>
</div>

1 个答案:

答案 0 :(得分:1)

您的DOM遍历不太正确。您可以使用closest()prev()来修复和简化它,如下所示:

$('a[name=outage]').closest('.modAcContent').prev('.modAcTitle').addClass('outage');

Updated fiddle