I need to clone an element's text, say an h1. I'm using jQuery's clone(), but I just want to copy the text and not the h1 tag so I can insert it into an h3 tag. I've tried using text() after the .clone(), but it doesn't work.
I need to clone an element's text, say an h1. I'm using jQuery's clone(), but I just want to copy the text and not the h1 tag so I can insert it into an h3 tag. I've tried using text() after the .clone(), but it doesn't work.
Share Improve this question asked Dec 13, 2010 at 1:36 CofeyCofey 11.4k16 gold badges54 silver badges75 bronze badges1 Answer
Reset to default 6It depends what you're after, but it sounds like you just want to set the text to the same thing, like this:
$("h3").text($("h1").text());
The alternative is to .append()
the .text()
of the <h1>
, which you can do directly like this:
$("h3").append($("h1").text());
But, as @bobince points out below this can be dangerous in some situations, let's take a simple one:
<h1><script>alert("hi, I'm malicious script");</script></h1>
You can see it in action here...you can imagine how this could be problematic with some nasty script.