简体   繁体   中英

How to add anchor tag to text inside a list

I have this list

<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>

I wanted to wrap all the Text inside the list with anchor tag for example something like this

<ul>
<li><a href="">Test</a></li>
<li><a href="">Test</a></li>
<li><a href="">Test</a></li>
<li><a href="">Test</a></li>
</ul>

Using jquery. The content is created dynamically so i dont have any control over the code to edit.

I used this code from some tutorial but no success.

$("ul li").wrap(function() {
   var link = $('<a/>');
   link.attr('href', '');
   link.text($(this).text());
   return link;
});

You can use wrapInner

 $('ul li').wrapInner('<a href="#"/>'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul> 

 $('ul li').contents().wrap('<a href="#"></a>'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul> 

Simply Use .wrap() in jquery

$('ul li').contents().wrap('<a />');

if you want add href attribute in the anchor tag

$('ul li').contents().wrap('<a href="#"></a>');

Fiddle

(function($) {
  $(function() {
    $('ul li').each(function() {
      var li = $(this),
        text = li.text();

      // li.html('<a href="">' + text + '</a>');
      li.text('').append('<a href="">' + text + '</a>');
    });
  });
})(jQuery);

li.html('<a href="">' + text + '</a>'); would pretty much remove everything in each li , since I dont know if that doesnt matter or not it's safer to remove the text and append an <a> using li.text('').append('<a href="">' + text + '</a>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM