Get the correct placeholder color with JS

Viewed 407

I changed the default placeholder color for my input to blue. Why do I get a black placeholder color with Javascript?

const getPlaceholderColor = () => {
  let inputEl = document.querySelector('.myClass');
  let inputElStyle = window.getComputedStyle(inputEl, '::placeholder');
  
  let resultTarget = document.getElementById('colorResult');
  let placeholderColor = inputElStyle.getPropertyValue('color');
  resultTarget.innerHTML = `Placeholder color: ${placeholderColor}`;
}
.myClass::placeholder {
  color: #004085;
}

.marginTop20 {
  margin-top: 20px;
}
<input
  type="text"
  placeholder="Enter name"
  class="myClass"
/>

<button onClick="getPlaceholderColor()">Get placeholder color</button>

<div class="marginTop20" id="colorResult"></div>

1 Answers

The problem is written about here => https://css-tricks.com/almanac/selectors/p/placeholder/

Below is a codepen that uses :placeholder-shown and ::placeholder

https://codepen.io/kipomaha/pen/pOOdQr

document.getElementById("myStyles").sheet.insertRule('.myClass:placeholder-shown { color: red; }');
document.getElementById("myStyles").sheet.insertRule('.myClass::placeholder { color: red; }');
const getPlaceholderColor = () => {
    let inputEl = document.querySelector('.myClass');
    let inputElStyle = window.getComputedStyle(inputEl, ':placeholder-shown');
    let resultTarget = document.getElementById('colorResult');
    let placeholderColor = inputElStyle.getPropertyValue('color');

    resultTarget.innerHTML = `Placeholder color: ${placeholderColor}`;
}


document.getElementById("myStyles").sheet.insertRule('.myClass:placeholder-shown { color: red; }');
document.getElementById("myStyles").sheet.insertRule('.myClass::placeholder { color: red; }');

var inputEl = document.querySelector('.myClass'); 
var placeholderColor = inputElStyle.getPropertyValue('color');
const getPlaceholderColor = () => {
    let inputElStyle = window.getComputedStyle(inputEl, ':placeholder-shown');
    let resultTarget = document.getElementById('colorResult');

    resultTarget.innerHTML = `Placeholder color: ${placeholderColor}`;
}
Related