Add class and insert before div

2019-07-26 03:56发布

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?

My Current 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>

Desired Output

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

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

1条回答
姐就是有狂的资本
2楼-- · 2019-07-26 04:19

you can use .prev method for that.

.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');
查看更多
登录 后发表回答