4

I am working on company website that is using placeholder attributes

I need to retrieve the color styling of this ATTRIBUTE ONLY, not from the input element itself.

It is being styled using --webkit-input-placeholder:

::-webkit-input-placeholder {
        color: red;
    } 

Unfortunately when I try to retrieve the value using javascript:

var color = window.getComputedStyle(document.querySelector('[class=abc]'),
'::-webkit-input-placeholder').getPropertyValue('color');

I get the wrong color result:

rgb (0, 0, 0)

Which should be:

rgb (255, 0, 0)

Here is a fiddle with an example : https://jsfiddle.net/darnold24/6q1pr5cf/

Any help I can get would be very much appreciated :) I also have access to jQuery, but my understanding is that it could only retrieve properties of elements, not attributes.

  • Note attributes have no styles. You probably mean you want to retrieve the color of the pseudo-element. – Oriol Feb 18 '15 at 20:35
  • This is not possible with JS to my knowledge, since pseudo elements are not part of the DOM. – Adrift Feb 18 '15 at 21:14
  • Yes, I also can't find a way to access it and it seems really not possible. See also this [SO question](http://stackoverflow.com/questions/14967250/jquery-change-placeholder-text-color) which is simillar to your question. – AWolf Feb 18 '15 at 21:16

1 Answers1

2

It's surprising that you can't access a pseudo element style that's defined in your own CSS.

Fortunately, you can get it by iterating through document.styleSheets:

var st= document.styleSheets;
for(var i = 0 ; i < st.length ; i++) {
  var rules= st[i].cssRules;
  for(var j = 0 ; j < rules.length ; j++) {
    var css= rules[j].cssText;
    if(rules[j].selectorText.indexOf('::-webkit-input-placeholder') > -1) {
      console.log(rules[j].style.color);  //red
    }
  }
}
::-webkit-input-placeholder {
  color: red;
}
<input id="myPlaceHolder" class="abc" type="text" placeholder="Sample Placeholder" />
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79