tags:

views:

56

answers:

5

Hi,

What I'm trying to do is to take paragraph containing a link, e.g.:

<p>this is a <a href="#">link</a> to something</p>

... and modify it with jQuery so the link contains all the paragraph text, e.g.:

<p><a href="#">this is a link to something</a></p>

I can't seem to get my head around this at the mo.

Cheers, James

+1  A: 

Remove everything from the p using 'empty' and then 'append' the href to the p.

matpol
+1  A: 

Use text().
In your specific case:

$('p').each(
  function()
  {
     var $this = $(this);  //more than 1 reference, I store it in a variable
     var address = $this.find('a').attr('href');
     //$this.text() includes children elements' text
     $this.html('<a href="' + address + '">' + $this.text() + '</a>');
  }
);
Alex Bagnolini
+1  A: 

You need to be able to select the paragragh and the anchor. So maybe if they had ids that would help.

 <p id="p">this is a <a id="a" href="http://www.google.com"&gt;link&lt;/a&gt; to something</p>

Then:

 var orig = $("#p").text();

var a = $('#a').text(orig);
$("#p").empty("");
$("#p").html(a);
Vincent Ramdhanie
+1  A: 
$("p > a").each(function(el) {
  var parent = $(this).parent();
  var text = parent.text();

  parent.replaceWith("<a href="+$(this).attr('href')+">"+text+"</a>");
});

What this does, is go through all your anchor tags inside paragraphs, get the only the text part and replace the paragraphs (the parent var) with a new anchor tag containing the same href attribute and the extracted text.

Andre Goncalves
This works well - I've modified <a href="+$(this).attr('href')+">"+text+"</a> to <p><a href="+$(this).attr('href')+">"+text+"</a></p> (so it retains the paragraph).
james6848
+1  A: 

Try this:

        $(function() {
            var link = $("<a href='#'></a>");
            var text = $("p a").parent().text();            

            $("p").replaceWith($(link).append(text));
        });
Colour Blend