JQuery add link to text

Is there a way in jQuery to select text from an html document and add a link around it?

Thanks a lot Nav

+4
source share
3 answers

You can use jQuery wrap function:

 $(someSelector).wrap(function() { var link = $('<a/>'); link.attr('href', 'somewhere_far_far_away'); link.text($(this).text()); return link; }); 
+13
source

You can do it as below.

  var txtN=$("#div").text(); var htmlStr=<a href="">txtN</a> 

then type htmlStr in html ...

You can use absolute positioning to set the position.

+3
source

This is how I do it. Suppose you need to do this on an h3 tag:

 var h3tag = $('h3#head'); var txt = h3tag.text(); h3tag.text(''); //Remove default text $("<a />", { "href" : $('h2 a').attr('href'), //grab the link from somewhere "text" : txt }).appendTo(h3tag); 

Hope this helps.

-1
source

All Articles