Add class and insert before div

无人久伴 提交于 2019-12-11 13:58:48

问题


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:


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');


来源:https://stackoverflow.com/questions/17202064/add-class-and-insert-before-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!