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

Time:12-13

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  id="quotedes">
    <p>Hello</p>
 </code>
<p>default text </p>
<button id="copyto">Click
</button>

CodePudding user response:

You have to set new color to <p> tag. It is important for style priority.

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

CodePudding user response:

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  id="quotedes">
    <p>Hello</p>
 </code>
<p>default text </p>
<button id="copyto">Click
</button>

CodePudding user response:

    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  id="quotedes">
    <p>Hello</p>
 </code>
<p>default text </p>
<button id="copyto">Click
</button> 
#enter code here#
<body>
<script>
const btn = document.getElementById("copyto/");
const para = document.querySelector("p");
btn.addEventListener("click", function () {
para.quotedes = "colorRed";
});
</script>
<body>

CodePudding user response:

put your js script inside body tag

  • Related