Link to home
Start Free TrialLog in
Avatar of skij
skijFlag for Canada

asked on

jQuery: Place content between matching comments inside special tags

Using jQuery, how can I put the content that is between the comments containing "RED" and the comments containing "/RED" inside <em> tags?

In the example below,
World
should become:
<em>World</em>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello World</title>
<style type="text/css">
em {color: red}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function () {

  $("*").contents().each(function(i,e){
    if (e.nodeType===8) {
      // ??
    }
  });

});

</script>
</head>
<body>
<h1>Hello <!-- RED -->World<!-- /RED --></h1>
<div><p>Hello <!-- RED -->World<!-- /RED --></p></div>
</body>
</html>

Open in new window

Avatar of Rob
Rob
Flag of Australia image

$(function() {
  $("*").contents().each(function(i,e){
    if (e.nodeType===8) {
    //  console.log("|"+e.data+"|");
      if(e.data.indexOf("/RED")>-1) {
        console.dir(e.previousSibling.textContent);
      }
    }
  });
});

Open in new window

Avatar of skij

ASKER

Thanks, but what I am trying to do is to put the content between the comments INSIDE <em> tags.

For example,
World
should become:
<em>World</em>

because it is between two matching comments.
ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of skij

ASKER

Thank you.  I have asked a related question here, to address if there are other tags between the comments:
https://www.experts-exchange.com/questions/28687194/jQuery-Place-deep-content-between-matching-comments-inside-special-tags.html