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
<a>
with a
<span>
but it replaces submenus elements also. I don't want that. Here's an example jsfiddle

Answer

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="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main-menu">
  <ul>
    <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>
  </ul>
</div>

Comments