在div之前添加类并插入 [英] Add class and insert before div

查看:216
本文介绍了在div之前添加类并插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将类"wp"添加到"sub-menu dropdown-menu"类之前的每个锚标记中.我该怎么做?

I would like to be able to add the class "wp" to each anchor tag that is before my "sub-menu dropdown-menu" class. How do I do this?

我当前的HTML:

  <a href="google.com">one</a>

  <ul class="sub-menu dropdown-menu">
   <li id="menu-item-5">
    <a href="">five</a>
  </li>
  </ul>

  <a href="google.com">one</a>
  <ul class="sub-menu dropdown-menu">
    <li id="menu-item-5">
      <a href="">five</a>
    </li>
  </ul>

所需的输出

 <a href="google.com" class="wp">one</a>

 <a href="google.com" class="wp">one</a>

推荐答案

,您可以使用.prev方法.

.prev('a')仅在找到选择器时才找到它的前一个直接同级.

.prev('a') finds the previous immediate sibling of the selector only if it finds it.

$('.sub-menu.dropdown-menu').prev('a').addClass('wp');

检查小提琴

Check Fiddle

为使它更好地工作,您也可以尝试

To make it work better you can try this as well

$('.sub-menu.dropdown-menu').prevAll('a').first().addClass('wp');

这篇关于在div之前添加类并插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆