Tony Babb
Tony Babb

Reputation: 85

Cloned div is different from the original

I'm creating a search feature for a smartphone app. It identifies the div containing the searched for term and appends it to an empty search results div. This is working fine. I'm trying to prevent multiple identical search results being displayed, this generally works but creates one duplicate search result.

It looks like the cloned and original text is different I've set up a jsfiddle here http://jsfiddle.net/tonybabb/2mwr3hp2/3/ illustrating the problem.

Html:

<div id="originalText">
some text
</div>
<div id = "copiedText">
</div>

Javascript:

var $originalText = $("#originalText").text();
$("#originalText").clone(true, true).appendTo("#copiedText");
if ("$originalText".match($("#copiedText").text())) {
    alert("Theyre the same");
} else {
    alert("Theyre different");   
}

I have been working on this for several days now, I'd really appreciate some advice. Thanks.

Upvotes: 0

Views: 46

Answers (4)

empiric
empiric

Reputation: 7878

I don't know if you need the clone, so that possibly event-handler are staying attached but here is another approach, which is working:

var $originalText = $("#originalText").text();
$("#copiedText").append($("#originalText").html());
if ($originalText.match($("#copiedText").text())) {
    alert("Theyre the same");
} else {
    alert("Theyre different");
}

In this solution, only the containing html is copied to the other div.

Furthermore: Your variable $originalText is containing a string already, so you don't have to put that in quotes to compare it via .match()

Demo

Upvotes: 1

redelschaap
redelschaap

Reputation: 2834

First, remove the quotes around "$originalText". Second, it doesn't work because of the line breaks in your html. The following works:

<div id="originalText">some text</div>
<div id="copiedText"></div>

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

Do the following,

1.remove quotes from "$originalText" 2. You should use $("#copiedText").find("div").text(), since the cloned div is attached to $("#copiedText")

var $originalText = $("#originalText").text();
$("#originalText").clone(true, true).appendTo("#copiedText");
if ($originalText.match($("#copiedText").find("div").text())) {
        alert("Theyre the same");
}
else {
 alert("Theyre different");   
}

Fiddle

Upvotes: 1

DLeh
DLeh

Reputation: 24395

You're not matching the text, you're checking if the literal string "$originalText" matches $('#copiedText').text()

Also, look at the rendered HTML, this is copying the whole div into the other div, not just the text.

Upvotes: 2

Related Questions