Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can read a :before {content:'...'} string via JavaScript (getComputedStyle), but this string behaves weirdly

Tags:

javascript

css

I have the follwing setup. I create a <div>, attach the term "before" through the pseudo-selector :before and read that value by using getComputedStyle.

This works, I get the term (which in my case is "before") successfully, it is of type "string". (See the console output.)

The comparison of that string with a given string returns the expected true, but only in Safari, CodePen and here, in the "Run code snippet"-Environment!

It does NOT work in Chrome, Firefox, or IE. The comparison of the match there returns false.

What could be the reasons for it?

Why does this simple string-comparison not work?

The three relevant snippets of code look like this:

var content = window.getComputedStyle(document.querySelector('.pseudo'), '::before').getPropertyValue('content');
console.log('content: ' + content); // "before"
console.log('typeof content: ' + typeof content); // string
console.log(content == "before"); // false
document.write(content == "before"); // false
div.pseudo:before {
  content: "before";
  color: red;
}
<div class="pseudo">
  Div with pseudo :before content.
</div>
like image 750
lotte-k Avatar asked May 07 '15 11:05

lotte-k


1 Answers

I found that different browsers treat getPropertyValue for content differently. Some browsers return literal quotes in the string, others don't.

Here is the fiddle that I used to test the behaviour across different browsers. The results below:

                                 | before | "before"
---------------------------------+--------+---------
Chrome 42.0.2311.135             | true   | false 
Chrome Canary 44.0.2394.0        | false  | true 
Firefox 37.0.2                   | false  | true
Firefox Developer Edition 39.0a2 | false  | true
Internet Explorer 11.09          | false  | true
Safari 8.0.5                     | true   | false
Opera 29.0.1795.47               | true   | false

Markup:

<div class="pseudo">Div with pseudo :before content.</div>

The CSS:

div.pseudo:before {
    content:'before';
    color: red;
}

The JS:

var content = window.getComputedStyle(document.querySelector('.pseudo'), '::before').getPropertyValue('content');

console.log(content == "before");
console.log(content == '"before"'); 
like image 61
mrkiffie Avatar answered Sep 24 '22 05:09

mrkiffie