Good evening, how can I replace the contents of block92

<!-- <block92> --> <tr> <div> </div> </tr> <!-- </block92> --> 

make a replacement via JS, to get:

 <!-- <block92> --> <salam> </salam> <!-- </block92> --> 
  • And what's in front of <!-- <block92> --> ? - Roman Grinyov
  • @RomanGrinyov <td valign = "top">, etc., approximately 500 lines of code. - developer
  • @developer, div in tr, wrapped in td, very strange code - MasterAlex
  • Edit the question ( Править button): give more code. That parents are interested in <!-- <block92> --> and what is in front of him. In general, to make the DOM tree visible. - Roman Grinyov
  • Look for the comment node (Node.nodeType === 8) in the ancestor and there already look for the desired comment. - user207618 6:49 pm

1 answer 1

It was most interesting to implement and remember JavaScript at the same time, so I wrote the following function, calling it insertNodeIntoCommentBlock() . This function cuts everything that is after the opening comment tag (first argument: commentBlock ) and before the closing comment tag, replacing the cut content with the passed node (second argument: node ) if it was passed (that is, the second argument is optional):

 <!-- <tag> --> всё, что находится здесь, будет вырезано; а если был передан узел вторым аргументом, то он будет вставлен вместо уничтоженного контента <!-- </tag> --> обратите внимание, что последний тег-комментарий — закрывающий, то есть со слешем: </...> 

The main problem lies in fetching the opening comment tag without iterating over the entire DOM tree.

...

Since you did not provide a full tree, I pushed away from document.body .

The result can be viewed through the code inspector.

I changed the layout a bit to show that everything inside is cut out, including comments and the nodes following them.

 var commentBlock = document.body.firstChild.nextSibling; var node = document.createElement('salam'); insertNodeIntoCommentBlock( commentBlock, node ); function insertNodeIntoCommentBlock( commentBlock, node ) { while ( commentBlock.nextSibling ) { if ( commentBlock.nextSibling.nodeType === 8 && commentBlock.nextSibling.data.replace('/', '') === commentBlock.data ) { break; } commentBlock.nextSibling.parentNode.removeChild( commentBlock.nextSibling ); } if ( node ) { commentBlock.nextSibling.parentNode.insertBefore( node, commentBlock.nextSibling ); } }; 
 <!-- <block92> --> <tr> <div> </div> </tr> <!-- </block> --> <blablabla></blablabla> <!-- </block92> --> blablabla 

https://jsfiddle.net/5ye8ger4/