Remove text in HTML page not inside element tag

Viewed 665

This is probably a very novice question but not sure how one could achieve this. There is an html page that shows as follows

<html>
   <body>
      <div><p>Hello!</p></div>
      <"
   </body>
</html>

My question is, is there a way to either remove or color the <" which is outside an html element via javascript or css?

4 Answers

Converting Pablo Salazar's answer to use vanilla JavaScript, no need for a massive library. Also going with the "colour it" option.

[...document.body.childNodes].filter(n=>n.nodeType === Node.TEXT_NODE)
    .forEach(n=>{
        const wrapper = document.createElement('span');
        wrapper.style.color = 'red';
        n.replaceWith(wrapper);
        wrapper.append(n);
    });
 <div><p>Hello!</p></div>
<"

You can do it with Jquery using this:

$('body').contents().filter(function(){ return this.nodeType != 1; }).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<html>
 <div><p>Hello!</p></div>
 
 <"

</html>

Dangerous way

var body_element = document.querySelector('body');
body_element.innerHTML = body_element.innerHTML.replace(/(&lt;"|<")/, '');
<html>
   <body>
      <div><p>Hello!</p></div>
      <"
   </body>
</html>

You can use nextSibling property and then .remove() mehtod

document.querySelector('div').nextSibling.remove();
<div>
    <p>Hello!</p>
</div>
<" 

Related