Gallex Gallex - 5 months ago 8
jQuery Question

Replace main menu's first and second items A element with SPAN

My solution below is almost working:

$('#main-menu > ul > li:nth-child(1) a, #main-menu > ul > li:nth-child(2) a').replaceWith(function() {
return '<span>' + $(this).text() + '</span>'

It replaces
with a
but it replaces submenus elements also. I don't want that. Here's an example jsfiddle


You need to add > before <a> as using this way #main-menu > ul > li:nth-child(1) a means all the <a> in <li>. Adding > will restrict it two first child only.

$('#main-menu > ul > li:nth-child(1) > a,#main-menu > ul > li:nth-child(2) > a').replaceWith(function() {
return '<span>' + $(this).text() + '</span>'
<script src=""></script>
<div id="main-menu">
    <li><a href="#">item1</a></li>
    <li><a href="#">item2</a></li>
    <li><a href="#">item3</a></li>
    <li><a href="#">item4</a></li>
    <li><a href="#">item5</a></li>