I tried this
if ($('nav li.menu-item-has-children:has(ul)'))
$ ('nav li.menu-item-has-children a').append ( "<span class="plus-minus">+</span>");
but all the anchor tags child menus are also getting the same HTML element Added
this is the menu structute
<ul id="primary-menu" class="menu">
<li class="menu-item "><a href="home/">Home</a></li>
<li class="menu-item" ><a href="about">About <span class="plus-minus">+</span></a>
<ul class="sub-menu">
<li class="menu-item"><a href="basics/">Basic</a></li>
</ul>
</li>
<li class="menu-item menu-item-has-children"><a href="products" aria-current="page">Products</a>
<ul class="sub-menu">
<li class="menu-item"><a href="Product-1">Product-1</a></li>
<li class="menu-item "><a href="Product-2">Product-2</a></li>
<li class="menu-item "><a href="Product-3">Product-3</a></li>
<li class="menu-item "><a href="Product-4">Product-4</a></li>
<li class="menu-item "><a href="Product-5">Product-5</a></li>
<li class="menu-item "><a href="Product-6">Product-6</a></li>
</ul>
</li>
<li class="menu-item"><a href="contact-us/">Contact Us</a></li>
</ul>
i want it to be
<ul id="primary-menu" class="menu">
<li class="menu-item "><a href="home/">Home</a></li>
<li class="menu-item" ><a href="about">About <span class="plus-minus">+</span> </a>
<ul class="sub-menu">
<li class="menu-item"><a href="basics/">Basic</a></li>
</ul>
</li>
<li class="menu-item menu-item-has-children"><a href="products" aria-current="page">Products <span class="plus-minus">+</span></a>
<ul class="sub-menu">
<li class="menu-item"><a href="Product-1">Product-1</a></li>
<li class="menu-item "><a href="Product-2">Product-2</a></li>
<li class="menu-item "><a href="Product-3">Product-3</a></li>
<li class="menu-item "><a href="Product-4">Product-4</a></li>
<li class="menu-item "><a href="Product-5">Product-5</a></li>
<li class="menu-item "><a href="Product-6">Product-6</a></li>
</ul>
</li>
<li class="menu-item"><a href="contact-us/">Contact Us</a></li>
</ul>
if ($('nav li.menu-item-has-children:has(ul)'))
$ ('nav li.menu-item-has-children a').append ( "<span class="plus-minus">+</span>");
3
Answers
Both of those lines have incorrect semantics:
The return value of the
$()
function would always be a jQuery object so the condition would always evaluate totrue
. You could do this insteadbut hold on because it’s unnecessary.
appends the
<span>
element to all elements matching the selector. The:has()
in the other line has no effect on that selector.What I’m assuming you actually want is
With no
if
. It would select all elements which are descendants ofnav li.menu-item-has-children:has(ul)
, and append the<span>
element to them.Because you are appending span element to every anchor tag under
li.menu-item-has-children
class.Your can use
>
selector.Try replacing this line.
Try out this: