最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to just clone text using jQuery's clone()? - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 6

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>&lt;script&gt;alert("hi, I'm malicious script");&lt;/script&gt;</h1>

You can see it in action here...you can imagine how this could be problematic with some nasty script.

发布评论

评论列表(0)

  1. 暂无评论