K48 K48 - 3 months ago 6
CSS Question

Replace text in a span that also contains other DOM elements

I have a code like this and I need to remove the

​
characters that are inserted automatically by the code that I have no control over (generated by SharePoint). They ruin the layout by inserting extra empty lines:

<div id="ctl00_PlaceHolderMain_ctl01__ControlWrapper_RichHtmlField" class="ms-rtestate-field" style="display:inline" aria-labelledby="ctl00_PlaceHolderMain_ctl01_label">
&#8203;&#8203;&#8203;
<span> &#8203;
<div class="cg-division-intro-outer">
<div class="cg-division-intro-inner">
<div class="cg-division-intro-header">
<h1>Division Intro</h1>
</div>

... etc


Notice that the
&#8203;
entities are inserted as bare text, not wrapped into any element, so I cannot target them directly.

Here is what I tried:


  1. Using
    visibility: hidden
    on the element containing the garbage and visibility: visible on my code. Has no effect.

  2. Reducing
    font-size
    on the parent element containing the garbage to 0px and restoring the font-size on other elements. Has no effect.

  3. Obtaining the
    innerHTML
    of the parent element, doing the
    .replace()
    and reinserting HTML back into the page - but then all the nodes will be lost/recreated, which means any attached listeners may be lost.

  4. Tried using :not but didn't come up with a solution that works.



Here is the white bar created by those
&#8203;
s:

enter image description here

Answer

DEMO

JS

use childNodes and change its value by nodeValue

var d = document.getElementById('div1').childNodes[0];
d.nodeValue = "new text"; // change value

// if you want to remove the element
d.parentElement.removeChild(d)

HTML

<div id="div1">
  some texts
  <div id="div2">
    other elements
    <div>hkeqvdkqbdklq</div>
  </div>
</div>