3

Is it possible that we could edit text enclosed inside an HTML comment using Javascript or JQuery. For example if I have a comment like:

<!-- This is a comment --> 

then is it possible to change text 'This is a comment' using JQuery or Javascript?

Thanks.

3
  • Of course. That's the whole point of jQuery, manipulating the DOM. See this api.jquery.com/text Commented Apr 1, 2015 at 12:07
  • Ah. I see you have edited your post (or Rory did :) You want to change what's inside a comment. That's completely different. Commented Apr 1, 2015 at 12:10
  • 2
    What do you want to achieve by doing this? Commented Apr 1, 2015 at 12:19

2 Answers 2

4

You can iterate through childNodes of the comment's parent element, filter the commentNode and change it's value by resetting nodeValue property:

$('#parent').contents().each(function() {
    if ( this.nodeType === 8 ) {
       this.nodeValue = 'changed value';
    }
});

Using vanilla JavaScript:

var parentNode = document.getElementById('parent');

[].forEach.call(parentNode.childNodes, function(el) {
    if ( el.nodeType === 8 ) {
       el.nodeValue = 'changed value';
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the replace() function like this:

var x =  $.trim($('#container').html()).replace('<!--','').replace('-->','');

There is also a plugin which you can use to uncomment is a jQuery plugin that will allow you "move" commented HTML code into the DOM

EDIT:-

If you want to remove it from the DOM as Rory commented then you can try this:

 $('*').contents().each(function() 
 {
        if(this.nodeType == Node.COMMENT_NODE) 
        {
            $(this).remove()
        }
 });

2 Comments

Note that this will make the comment of the text visible in the DOM, it will not retain the comment and change the text within it - which is what the OP seems to be looking to do.
@RoryMcCrossan:- Updated my answer to remove it from the DOM as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.