jQuery: Place combined content between matching comments inside special tags

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

All the content between the matching tags should be grouped inside a single set of <em> tags.  The problem with the example below is that many sets of <em> tags are created.

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Demo</title>
<style type="text/css">em{color:red; border: 1px solid red;}</style>
<script type="text/javascript">
$(function() {
  $("*").contents().each(function(i,e){
    if (e.nodeType===8) {
      if(e.data.indexOf("/RED")>-1) {
        var t = e.previousSibling; 
        while (t.nodeType!==8) {
            if(t.nodeType && (t.nodeType===1 || t.nodeType===3)) {
              $(t).wrap("<em>");
              t = t.parentNode.previousSibling;
            }
            else {
              t = t.previousSibling;
          }
        }
      }
    }

  });
});
</script>
</head>
<body>

 <h1>Lorem <!-- RED --> consectetur <strong>ipsum</strong> <u>eleifend</u> dolor<!-- /RED --> sit amet</h1>
 <div><p>Donec <!-- RED --> <u>consectetur</u> pretium <u>lacus </u> amet<!-- /RED --> lobortis.</p></div>

</body>
</html>

Open in new window

https://jsfiddle.net/6Lhc6w3a/

One idea I had is to appendTo() instead of wrap().  Otherwise, maybe prevUntil() could be used with a filter.  I am open to any other ideas as well, as long as the desire result is accomplished.  Thanks!
LVL 10
skijAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Something like this?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Demo</title>
<style type="text/css">em{color:red; border: 1px solid red;}</style>
<script type="text/javascript">
$(function() {
	var replaced = $('body').html().replace(/\<\!-- RED --\>/g, '<em>').replace(/\<\!-- \/RED --\>/g,'</em>');
	$('body').html(replaced);
});
</script>
</head>
<body>

 <h1>Lorem <!-- RED --> consectetur <strong>ipsum</strong> <u>eleifend</u> dolor<!-- /RED --> sit amet</h1>
 <div><p>Donec <!-- RED --> <u>consectetur</u> pretium <u>lacus </u> amet<!-- /RED --> lobortis.</p></div>

</body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RobOwner (Aidellio)Commented:
I knew they'd be a simpler way!

(no points, julian's easily answered this one) - if you wanted to retain the comments you would just keep them in the replace:

$(function() {
	var replaced = $('body').html().replace(/\<\!-- RED --\>/g, '<!-- RED --><em>').replace(/\<\!-- \/RED --\>/g,'</em><!-- /RED -->');
	$('body').html(replaced);
});

Open in new window

skijAuthor Commented:
What are the implications for dynamic content such as JavaScript and jQuery triggers?  Would they respond to using replace the same was as they would to using things like .prependTo() or .wrap()?
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Julian HansenCommented:
Can you give an example?
skijAuthor Commented:
What if jQuery had been used to add an event to some of the content impacted by this?  
For example:
$(document).ready(function() {
    $("a").click(function() {
        //Do stuff when clicked
    });
});

Open in new window

Would using REGEX versus using a different method to manipulate the content have an impact of the way these events were handled?
Julian HansenCommented:
To make allowances for this do as follows (use the .on method)
$(function() {
    $("body").on('click','a', function() {
        //Do stuff when clicked
    });
});

Open in new window


That will ensure that even dynamically added content will retain its event handlers.
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.