Raul Leaño Martinet
Raul Leaño Martinet

Reputation: 2113

mootools replace the content of a div

i have the following HTML code

<div id="myDiv">
   <p>content</p>
</div>

and the following JS code:

$('myDiv').set('html',htmlCode);

the problem is that the variable htmlCode is something like:

<div id="myDiv"><p>another content</p></div>

so, the result when i run the JS code is something like:

<div id="myDiv">
   <div id="myDiv">
      <p>another content</p>
   </div>
</div>

is there a way to use "set" so that it overrides the entire div? or another solution to get something like:

<div id="myDiv">
   <p>another content</p>
</div>

as the result from the JS script? i know i could just change the variable htmlCode... i just was wondering if there's another solution to this.

Upvotes: 3

Views: 8097

Answers (4)

Zaje
Zaje

Reputation: 2309

You can do

$("myDiv").getParent().set("html", htmlCode);

Upvotes: 0

stecb
stecb

Reputation: 14746

Mootools offers a simple replaces method!

//new tmp element that contains the new div
var tmpDiv = new Element('div',{html:'<div id="myDiv"><p>another content</p></div>'});

//new div (first child of my tmp div) replaces the old 'myDiv' (that can be grabbed from the DOM by $)
tmpDiv.getFirst().replaces($('myDiv'));

Upvotes: 6

Medrod
Medrod

Reputation: 996

$('myDiv').empty();
$('myDiv').adopt(Elements.from(htmlCode).getElement('p'));

Upvotes: 4

Oskar Krawczyk
Oskar Krawczyk

Reputation: 3502

String.implement({
    replaces: function(toReplace) {
        Elements.from(this).inject(toReplace, 'after');
        toReplace.destroy();
    }
});

'<div id="a"><p>ipsum</p></div>'.replaces($('a'));

This should do. Example: http://jsfiddle.net/UvuwG/

Upvotes: 5

Related Questions