If I have that
<!-- some comment -->
How do I get this element and change the content with javascript? And if I have a code inside that and I want to delete the tag of comments how can I do it?
Yes, it is considered as a best practice, since this is to save our code from a browser that does not support JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code.
Multi-line comments start with /* and end with */ . Any text between /* and */ will be ignored by JavaScript.
In HTML, a comment is text enclosed within < ! ╌ ╌> tags. This syntax tells the browser that they are comments and should not be rendered on the front end. Thanks to the comments tag, you can leave notes to remind yourself where you left off in the build process.
The comment tag is used to insert comments in the source code. Comments are not displayed in the browsers. You can use comments to explain your code, which can help you when you edit the source code at a later date. This is especially useful if you have a lot of code.
The best method is to use a dedicated NodeIterator instance iterating all comments contained in a given root element.
See it in action!
function filterNone() { return NodeFilter.FILTER_ACCEPT; } function getAllComments(rootElem) { var comments = []; // Fourth argument, which is actually obsolete according to the DOM4 standard, is required in IE 11 var iterator = document.createNodeIterator(rootElem, NodeFilter.SHOW_COMMENT, filterNone, false); var curNode; while (curNode = iterator.nextNode()) { comments.push(curNode.nodeValue); } return comments; } window.addEventListener("load", function() { console.log(getAllComments(document.body)); });
If you have to support older browsers (e.g. IE <9), you need to traverse the DOM yourself and extract those elements whose node type is Node.COMMENT_NODE
.
See it in action!
// Thanks to Yoshi for the hint! // Polyfill for IE < 9 if (!Node) { var Node = {}; } if (!Node.COMMENT_NODE) { // numeric value according to the DOM spec Node.COMMENT_NODE = 8; } function getComments(elem) { var children = elem.childNodes; var comments = []; for (var i=0, len=children.length; i<len; i++) { if (children[i].nodeType == Node.COMMENT_NODE) { comments.push(children[i]); } } return comments; }
Independent of the way you choose from above, you receive the same node DOM objects.
Accessing a comment's contents is as easy as commentObject.nodeValue
.
Deleting a comment is a bit more verbose: commentObject.parentNode.removeChild(commentObject)
You have to travers the DOM to get it. The nodeType
of the comment DOM element is 8
if( oNode.nodeType === 8 ) { oNode.parentNode.removeChild( oNode ); }
would be an approach
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With