问题
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