user715564 user715564 - 5 months ago 7
CSS Question

Changing "<a>" to "<span>" on screen resize with jQuery

I need to replace an

a
tag in my
nav
with a
span
tag if the browser is resized below a certain
width
.

Here is my HTML:

<div class="menu-main-menu-container">
<ul>
<li><a href="">one</a></li>
<li>
<a href="">two</a>
<ul>
<li><a href="">one</a></li>
<li><a href="">two</a></li>
</ul>
</li>
<li>three</li>
</ul>
</div>


Here is my jQuery:

$( window ).on('load resize', function() {
if ($(window).width() < 478) {
$('.menu-main-menu-container ul li:nth-child(2) a').first().replaceWith(function() {
return $('<span>' + $(this).html() + '</span>');
});
}
});


Right now, everything works on load. If I resize the browser than all
a
tags are replaced with
span
tags.

Only the first
a
tag in the second
li
tag needs to be replaced with a
span
tag.

Answer

The problem here is your resize() function. Once the treshhold of 478px is reached, the correct a will be replaced. If you are now continue to resize the next a will match your selector because the first one is a span now.

If you know your HTML-structure is not dynamic and stays like this you can use the immediate child selector >:

$('.menu-main-menu-container > ul > li:nth-child(2) > a:first').replaceWith(function() {
     return $('<span>' + $(this).html() + '</span>');
});

Example