How to merge paragraphs into parent link with jquery / Javascript?

Go To StackoverFlow.com

0

How do I turn this:

<a class="link">
   <p class="paragraph">This is some text</p>
   <p class="paragraph">This is some more text</p>
   <p class="paragraph">And some more</p>
</a>

into this:

<a class="link">
   This is some text This is some more text And some more
</a>

with jQuery. I tried using append and merge but I just can't figure it out.

2012-04-04 21:30
by Tomi Seus


5

Since the text method returns the text content of an element and it's descendants, you can just use that:

var link = $("a.link");
link.text(link.text());​​​​​​​​​

From the docs:

Get the combined text contents of each element in the set of matched elements, including their descendants.

Here's a working example.

Update (see comments)

In the case that this needs to apply to multiple .link elements, you can use each:

$("a.link").each(function() {
    $(this).text($(this).text()); 
});
2012-04-04 21:31
by James Allardice
But what happens if a.link matches more than one element - Frédéric Hamidi 2012-04-04 21:34
much elegant solutio - DG3 2012-04-04 21:34
@FrédéricHamidi - Then it will replace the text of each with the text of all. I was assuming this would only apply to one element. See edit - James Allardice 2012-04-04 21:35
great, I actually do need it for multiple element - Tomi Seus 2012-04-04 21:48


4

This will work:

$("a.link").text(function(i,text){
    return text;
});

And yet another way (not tested):

// you can optionally filter to
// only p elements too with
// .children("p")
$("a.link").children().contents().unwrap();

Here's another variation of the second:

$("a.link p").contents().unwrap();

Edit: Just a note for clarity:
All of these solutions work on multiple elements. The first solution is a relatively uncommon syntax that can be used on most jQuery setter functions. It runs the callback on each matched element and sets the value of the property/attribute to the value returned from the callback.

2012-04-04 21:33
by Kevin B


0

try this

    $(document).ready(function(){
      var concatText = "";

      $("p.paragraph").each(function(){
       concatText = concatText + " " + $(this).text() 
      });

        $("a.link").html(concatText);
​     });​
2012-04-04 21:33
by DG3
Ads