Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diff two containers with JS or jQuery

I want to update a container with a new version without replacing it. For example:

Container1:

<div id="container-one">
    <p>
        <webview src="http://i.stack.imgur.com/Ed1aw.jpg"></webview>
    </p>
    <p>
       Text
    </p>
</div>

Container2:

<div id="container-two">
    <p>
        Cool intro
        <webview src="http://i.stack.imgur.com/Ed1aw.jpg"></webview>
    </p>
    <p>
       Long text
    </p>
    <p>
       New Paragraph with text in it.
    </p>
</div>

Container1 updated:

<div id="container-one">
    <p>
        Cool intro
        <webview src="http://i.stack.imgur.com/Ed1aw.jpg"></webview>
    </p>
    <p>
       Long text
    </p>
    <p>
       New Paragraph with text in it.
    </p>
</div>

A Container1.innerHTML = Container2.innerHTMLwould be simple but I don't want to reload my webview so the code should detect new divs or updated content in existing divs and apply the modifications in Container1.

UPDATE :

Container2 is a new version of container1 edited by a user, so Container2 can have anything in it: images, links, new paragraphs.

How can I do this?

like image 410
Armand Grillet Avatar asked Mar 29 '14 10:03

Armand Grillet


2 Answers

I might have not understood your question correctly, but by adding an id to the text that you want to replace, and using simple javascript, you can achieve this.

HTML

<div id="container-one">
    <p>
        <span id="inner-one-1"></span>
        <webview src="http://i.stack.imgur.com/Ed1aw.jpg"></webview>
    </p>
    <p>
       <span id="inner-one-2">Text</span>
    </p>
</div>

<div id="container-two">
    <p>
        <span id="inner-two-1">Cool intro</span>
        <webview src="http://i.stack.imgur.com/Ed1aw.jpg"></webview>
    </p>
    <p>
       <span id="inner-two-2">Long text</span>
    </p>
</div>

<button id="click">Click Me!</button>

JS

document.getElementById("click").onclick = function() {
    document.getElementById("inner-one-2").innerHTML = document.getElementById("inner-two-2").innerHTML;
    document.getElementById("inner-one-1").innerHTML = document.getElementById("inner-two-1").innerHTML;
}

DEMO HERE

like image 83
benomatis Avatar answered Sep 30 '22 15:09

benomatis


please try it.

var container_one = $("#container-one").children();
var container_two = $("#container-two").children();


$.each(container_one, function(index, element){
  var cont_one_html = $(this).html();
  var cont_two_html = $(container_two[index]).html();
  if(cont_one_html != cont_two_html){
    $(this).html(cont_two_html);
  }
});

please have a look on image enter image description herefor more understanding.

like image 24
uma Avatar answered Sep 30 '22 15:09

uma