Regular expression

G

Giacomo

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>





Thanks in advance, bye.

Giacomo
 
M

Martin Honnen

Giacomo said:
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);
}
}
 
R

RobG

Martin Honnen wrote:
[...]
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);
}
}

I like using firstChild:

while (div.firstChild){
div.removeChild(div.firstChild);
}


Another quick way to remove content is to replace the node with a
shallow clone of itself:

var div = document.getElementById('pippo');
if (div && div.cloneNode){
var oDiv = div.cloneNode(false);
div.parentNode.replaceChild(oDiv,div);
}


[...]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top