Giacomo wrote:
I obtained all the html code contained in a div by:
var all = getElementsByClassName('div','twikiTopic');
var result = all[0].innerHTML;
let's say that the code contained in "result" has this structure:
A
<div id="pippo">
B
</div>
C
when A,B and C is arbitrary html code. Using the function replace
(javascript) I'd like to remove all the code inside and following the
div with id="pippo", obtaining:
A
<div id="pippo">
</div>
Why on earth if the browser provides a structured DOM with element and
text nodes and methods to remove nodes do you serialize the DOM with
innerHTML to then try your luck with regular expressions? If you want to
manipulate the contents of all[0] then use the DOM to remove the nodes
you want to remove. If you want to keep the contents of all[0] but want
to manipulate a copy then clone that node and then use the DOM to
manipulate the cloned contents.
So for instance if you wanted to remove all child nodes of the <div
id="pippo"> element then you could do e.g.
var div = document.getElementById('pippo');
if (div != null) {
while (div.hasChildNodes()) {
div.removeChild(div.lastChild);
}
}
To additionally remove a sibling node of that div you could extend that to
var div = document.getElementById('pippo');
if (div != null) {
while (div.hasChildNodes()) {
div.removeChild(div.lastChild);
}
var sibling = div.nextSibling;
if (sibling != null) {
sibling.parentNode.removeChild(sibling);
}
}
--
Martin Honnen
http://JavaScript.FAQTs.com/