Search code examples
jquerywrapinner

Wrapping an element with an <a> that has a dynamic href jQuery


Got a series of list items, and I'm trying to wrap the content with links and add a dynamic href. It's wrapping the list item contents properly, but it's adding the href to the list item instead. What's wrong with my syntax here?

jQuery:

$('.menu ul li').each(function(i, e){
$(this).wrapInner('<a></a>').attr("href", "#" + "slide-" + i);
});

Base HTML:

<nav class="menu">
<ul>
<li>Child 1</li>
</ul>
</nav>

Current output for the list items:

<li href="#slide-0">
<a>Child 1</a>
</li>

Solution

  • .wrapInner() returns the element that was wrapped, not the wrapping element.

    Create the <a> element and add the attribute to that, then wrap that around the element.

    $('.menu ul li').each(function(i, e) {
      $(this).wrapInner($('<a>', {
        "href": "#" + "slide-" + i
      }));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <nav class="menu">
      <ul>
        <li>Child 1</li>
      </ul>
    </nav>