最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - mootools replace the content of a div - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Jan 10, 2011 at 23:04 Raul Leaño MartinetRaul Leaño Martinet 2,1136 gold badges29 silver badges44 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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'));
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/UvuwG/

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

You can do

$("myDiv").getParent().set("html", htmlCode);
发布评论

评论列表(0)

  1. 暂无评论