Faili
Faili

Reputation: 1000

Saving text and inserting it after a specified variable

there's a site with lots of comments.

code1
<p>hello ernie</p>
<p>this is mark</p>
<p>hello ben</p>
<p>this is ernie</p>
<p>hello mark</p>
<p>this is ben</p>

Now I want to collect all comments containing 'hello' and insert the phrases with hello after all comments.

$("p:contains('hello')").insertAfter($("#comments"));

'hello' is taken from the comments and inserted after the comments.

code2
<p>this is mark</p>
<p>this is ernie</p>
<p>this is ben</p>
code3
<p>hello ernie</p>
<p>hello ben</p>
<p>hello mark</p>

Is there a way to keep the comments as they were (code1) and still insert all comments containing 'hello' after the comments. Like

How it should look like.


<p>hello ernie</p>
<p>this is mark</p>
<p>hello ben</p>
<p>this is ernie</p>
<p>hello mark</p>
<p>this is ben</p>

<p>hello ernie</p>
<p>hello ben</p>
<p>hello mark</p>

Any hint or help is much appreciated.

Upvotes: 0

Views: 42

Answers (2)

Naeem Sarfraz
Naeem Sarfraz

Reputation: 7430

You could use .clone() like so:

$("p:contains('hello')").clone().insertAfter($("#comments"));

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630379

Use .clone() to create a copy then move only those copies, like this:

$("p:contains('hello')").clone().insertAfter("#comments");

Also .insertAfter() takes a selector directly, so no need to wrap it here.

Upvotes: 2

Related Questions