Search code examples
javascripthtmlcsscolors

Change text color style under <p> using JS if css style already defined


When there is already defined color style in css for p tag, using JS, cannot change the text color

var prelearnBtn = document.getElementById("copyto");
prelearnBtn.addEventListener("click", function() {
  setTimeout(function() {
    document.getElementById("quotedes").style.color = "blue";
  }, 100);
});
p {
  color: green;
  font-size: 25px;
}
<code class="quotedes" id="quotedes">
    <p>Hello</p>
 </code>
<p>default text </p>
<button id="copyto">Click
</button>


Solution

  • The code mentioned in the question works fine. Except in this when you are changing the color to blue, you are changing it with the code snippet id. it should be done for the paragraph. Therefore, I fetched the first child of that id and assigned a style to that element.

    var prelearnBtn = document.getElementById("copyto");
    prelearnBtn.addEventListener("click", function() {
      setTimeout(function() {
        let parentEle = document.getElementById("quotedes");
        parentEle.children[0].setAttribute('style',  "color:blue");
      }, 100);
    });
    p {
      color: green;
      font-size: 25px;
    }
    <code class="quotedes" id="quotedes">
        <p>Hello</p>
     </code>
    <p>default text </p>
    <button id="copyto">Click
    </button>