Reputation: 445
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
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';
}
});
var parentNode = document.getElementById('parent');
[].forEach.call(parentNode.childNodes, function(el) {
if ( el.nodeType === 8 ) {
el.nodeValue = 'changed value';
}
});
Upvotes: 4
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