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 .clo开发者_JS百科ne(), but it doesn't work.
It 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.
精彩评论