1

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?

12
  • How about Element.removeAttribute('style') ? Commented Jun 24, 2016 at 16:48
  • are you sure your javascript is correctly hooked up with the html? so do something like alert('test'); inside the click to make sure it is even registered. Commented Jun 24, 2016 at 16:48
  • Why you are not adding ID to that specific Span Commented Jun 24, 2016 at 16:48
  • 3
    Your HTML is invalid. A <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. Commented Jun 24, 2016 at 16:49
  • 1
    And now that you've edited your example, it works. Commented Jun 24, 2016 at 16:53

1 Answer 1

5

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/

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

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.