Mike-S122
Mike-S122

Reputation: 219

Move HTML Code between comment (incl. comments)

I have the below HTML special content between comments

<p>Regular text</p>
<p>Regular text</p>
<!--Special Content-->
<p>Special Content 1</p>
<p>Special Content 2</p>
<!--/Special Content-->
<p>Regular text</p>
<p>Regular text</p>
<p id="reference">Place special content with comments below this <p> element</p>

I need to wrap the HTML content between the comments <!--Special Content-->and <!--/Special Content--> including the comments themselves into a <div> and move it below the <p id="reference">element.

I have no access to the actual HTML template so it needs to be done via JavaScript or JQuery.

I haven't be able to find a way to wrap the content including the comments so far.

End result should be:

<p>Regular text</p>
<p>Regular text</p>
<p>Regular text</p>
<p>Regular text</p>
<p id="reference">Place special content with comments below this <p> element</p>
<div id="wrapper">
  <!--Special Content-->
  <p>Special Content 1</p>
  <p>Special Content 2</p>
  <!--/Special Content-->
</div>

I appreciate your ideas.

Upvotes: 1

Views: 144

Answers (2)

Lucas Shanley
Lucas Shanley

Reputation: 406

This will move all the content between your special comment tags after the reference id tag.

let move = false;
let parse = $('body').contents().each(function(k,v){

	if( v.nodeType === 8 ){
		if( v.nodeValue === "Special Content" ) move = true;
		else if( v.nodeValue === "/Special Content") move = false;
	}
	else if(move && v.nodeType === 1)
		$(v).insertAfter('#reference');
	
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Regular text</p>
<p>Regular text</p>
<!--Special Content-->
<p>Special Content 1</p>
<p>Special Content 2</p>
<!--/Special Content-->
<p>Regular text</p>
<p>Regular text</p>
<p id="reference">Place special content with comments below thiselement</p>

Upvotes: 0

Lucero
Lucero

Reputation: 60190

var dataElem = document.getElementById("data");

var doMove = false;
var toMove = [];

for (var i = 0; i < dataElem.childNodes.length; i++) {
  var node = dataElem.childNodes[i];
  if (node.nodeType === Node.COMMENT_NODE && node.data === "Special Content") {
    doMove = true;
  }
  if (doMove) {
    toMove.push(node);
  }
  if (node.nodeType === Node.COMMENT_NODE && node.data === "/Special Content") {
    doMove = false;
  }
}

var targetElem = document.createElement("DIV");
targetElem.setAttribute("id", "wrapper");
dataElem.insertBefore(targetElem, document.getElementById("reference").nextSibling);
for (var i = 0; i < toMove.length; i++) {
  targetElem.appendChild(toMove[i]);
}
<div id="data">
  <p>Regular text</p>
  <p>Regular text</p>
  <!--Special Content-->
  <p>Special Content 1</p>
  <p>Special Content 2</p>
  <!--/Special Content-->
  <p>Regular text</p>
  <p>Regular text</p>
  <p id="reference">Place special content with comments below this <p> element</p>
</div>

Upvotes: 2

Related Questions