views:

60

answers:

5

How can I wrap every element belonging to a particular class with a link that is built from the text inside the div? What I mean is that I would like to turn:

<foo class="my-class>sometext</foo>

into

<a href="path/sometext" ><foo class="my-class>sometext</foo></a>

Url encoding characters would also be nice, but can be ignored for now if necessary.

EDIT: Just to clarify, the path depends on the text within the element

+2  A: 

Use jQuery.wrap() for the simple case:

$(".my-class").wrap("<a href='path/sometext'></a>");

To process text inside:

$(".my-class").each(function() {
  var txt = $(this).text();
  var link = $("<a></a>").attr("href", "path/" + txt);
  $(this).wrap(link[0]);
});
cletus
+2  A: 
$(".my-class").each(function(){
  var thisText = $(this).text();
  $(this).wrap("<a></a>").attr("href","path/"+thisText);
});
Jonathan Sampson
+1  A: 

you can wrap them inside anchor element like this:

$(document).ready(function(){
    $(".my-class").each(function(){
           var hr="path/"+$(this).text();
           $(this).wrap("<a href='"+hr+"'></a>");
   });
});

if you are opening links in same page itself then easier way than modifying dom to wrap elements inside anchor is to define css for the elements so that they look like links then handle click event:

$(".my-class").click(function(){
     window.location.href="path/"+$(this).text();
});
TheVillageIdiot
Be careful with $(this).html(). Better to use $(this).text() to avoid any formatting tags getting included.
Jonathan Sampson
Yes you are right @Jonathan **.html()** fetch everything :)
TheVillageIdiot
A: 

This ought to do it:

$('foo.my-class').each(function() {
  var element = $(this);
  var text = element.html(); // or .text() or .val()
  element.wrap('<a href="path/' + text + '"></a>');
});
John Fisher
I think you meant $(element) instead of $element.
Jonathan Sampson
A: 
$("foo.my-class").each(function(){
  var foo = $(this);
  foo.wrap("<a href='path/" + foo.Text() +"'>");
});
Russ Cam