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.
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());
});
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.
try this
$(document).ready(function(){
var concatText = "";
$("p.paragraph").each(function(){
concatText = concatText + " " + $(this).text()
});
$("a.link").html(concatText);
});
a.link
matches more than one element - Frédéric Hamidi 2012-04-04 21:34