Reputation: 9918
I have a list going like the following:
<div id="menuContainer">
<ul id="menu">
<li><a href="#1">Main Item 1</a></li>
<li><a href="#2">Main Item 2</a>
<ul>
<li><a href="#21">Sub Item 2.1</a></li>
<li><a href="#22">Sub Item 2.2</a></li>
<li><a href="#22">Sub Item 2.3</a></li>
</ul>
</li>
<li><a href="#3">Main Item 3</a>
<ul>
<li><a href="#31">Sub Item 3.1</a></li>
<li><a href="#32">Sub Item 3.2</a></li>
</ul>
</li>
</ul>
</div>
I want to remove <a>
tags of "Main Items" only.
I have tried to use
$('#menuContainer > ul > li > a').replaceWith($('#menuContainer > ul > li > a').text());
But it's removed all the anchors including sub items. I want script to do it for the first level items only, not deeper ones.
Upvotes: 1
Views: 58
Reputation: 337560
You can provide replaceWith
with a function which provides the this
keyword to use as the reference for the current a
element. You can then return the text()
of the element to make the replacement.
$('#menuContainer > ul > li > a').replaceWith(function() {
return $(this).text();
});
Upvotes: 1