I'm trying to use replace() to get rid of style="border-top-color: green;" in a chunk of code. The example below shows that it's not working, and I don't understand why.
Doing alert(res); seems to indicate that the full chunk of code (the HTMl of <p id="demo">) doesn't seem to be being scanned by replace().
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(' style="border-top-color: green;"', '');
document.getElementById("demo").innerHTML = res;
}
<span id="demo">
Point: (11, 2)
<br>Slope: <span style="position: relative; top: 1px; left: -2px;">-</span>
<div class="fraction_display"><span class="numer_display">12</span><span class="bar_display">/</span><span class="denom_display">7</span>
</div>
<br>
<br>Point-Slope Form: y – 2 = <span style="position: relative; top: 1px; left: -2px;">-</span>
<div class="fraction_display"><span class="numer_display">12</span><span class="bar_display">/</span><span class="denom_display" style="border-top-color: green;">7</span>
</div>(x – 11)
</span>
<button onclick="myFunction()">Replace Fail</button>
Clicking "Replace Fail" will show you that the style="border-top-color: green;" is still present after it should have been removed. Thoughts?
1 Answer 1
This will fail because a <p> cannot contain a <div>. If you retrieve the inner html of an element with an illegal structure, it will return an unexpected string. So this:
var str = document.getElementById("demo").innerHTML
will return this and only this:
Point: (11, 2)
Slope: -
As soon as the browser hits the div it will stop returning anything past it. Therefore the string you want to replace is never returned, much less replaced.
You should ensure your markup is valid with W3C's validator: https://validator.w3.org/
Element.removeAttribute('style')?Span<p>cannot contain a<div>. Browsers know this and tend to try and compensate by closing the<p>, thereby changing the structure you intended to use.