1

In this thread: Uncomment html code using javascript

I found that all the solutions in the thread uses jQuery. I was just wondering how to do this in vanilla javascript without using third-party library?

This is not a duplicate question of How do I get an HTML comment with javascript, that thread discussed about how to find and delete the comment node but didn't say anything about how to "uncomment" it.

5
  • Possible duplicate of How do I get an HTML comment with javascript Commented May 23, 2016 at 7:42
  • @Quentin Thanks, I saw his/her answer, and found it used replaceWith method, which is a method of jQuery object. Commented May 23, 2016 at 7:45
  • @Rayon It is not duplicate, the thread discussed about how to find and delete the comment node but didn't say anything about how to "uncomment" it. Commented May 23, 2016 at 7:46
  • I guess finding it is difficult task.. replacing it should be easier..I could be wrong though :) Commented May 23, 2016 at 7:48
  • Maybe not the most efficient way, but by using .innerHTML and a regular expression to parse it? Commented May 23, 2016 at 7:50

2 Answers 2

3

One way would be to replace all <!-- --> with an empty string found by .innerHTML.

var content = document.getElementById('content');

content.innerHTML = content.innerHTML.replace('<!--', '').replace('-->', '');
<div id="content">
  <!-- <div>Hello</div> -->
  <h1>
    Title
  </h1>
</div>

Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

var tr = document.querySelector('table tr');
var children = tr.childNodes;
[].slice.call(children).forEach(function(child) {
  if (child.nodeType === 8) {
    var elem = document.createElement('div');
    elem.innerHTML = child.textContent;
    tr.replaceChild( elem.childNodes[0], child );
  }
});
<table>
   <tr>
         <td>ABCD</td>
         <td>Logic</td>
         <!-- <td>26538568</td> -->
   </tr>
</table>

Comments

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.