user1404963
user1404963

Reputation: 445

Edit HTML Comment Text using JQuery or Javascript

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.

Upvotes: 3

Views: 1504

Answers (2)

Ram
Ram

Reputation: 144739

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';
    }
});

Upvotes: 4

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

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()
        }
 });

Upvotes: 0

Related Questions