Search code examples
javascriptjqueryhtmlupdating

Prevent element from updating - JQuery


I select an element of the page:

$mainSection = $('#main');

then I add more Elements via AJAX into the <div id="main"></div> element. Next time I call $mainSection, the newly added elements are also in it. But I don't want that. I would like that the variable $mainSection only has the content in it from the initial rendering of the page. I can't find a way to prevent jQuery from updating.


I tried this:

$(document).ready(function(){
  $mainSection = $('#main').clone(true);

Then I add new elements to #main and then I check if they get found via:

$foundElement = $($mainSection + ":not(:has(*)):not(script):contains('"+newlyAddedContent+"')");

On page load, they are not there. But after I add them, they get found.

I also tried:

$mainSection = $('#main').html();
$mainSection = $($mainSection);

didn't work also.


Here is a jsFiddle to illustrate my point:

http://jsfiddle.net/VEQ2E/2/


The problem is somewhere burried in this line: $foundElement = $($mainSection + ":not(:has(*)):not(script):contains('"+newlyAddedContent+"')");

It somehow always searches through the whole document, when I do it like this.


Solution

  • Your problem was not that your clone was getting changed, but rather the selector you were using to try finding something within the clone. Your code was like this:

    $($mainSection + ":not(:has(*)):not(script):contains('"+newlyAddedContent+"')");
    

    Concatenating an object with a string will turn the object into a string, simply "[object Object]", then your selector will just look at the ":not(:has..."

    Instead, you should use filter:

    $foundElement = $mainClone.filter(":not(:has(*)):not(script):contains('world')");
    

    This will now only look within your $mainClone for items matching that filter.

    JSFiddle