0

This is so simple I have no idea why it's not working. I am trying to get a CSS variable value with jQuery and compare it to a string of the same value. The comparison should return true while it does not.

var themeMode = $(document.body).css('--theme-mode');
console.log(themeMode);
console.log(themeMode == 'dark');
:root {
  --theme-mode: dark;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
halfer
  • 19,824
  • 17
  • 99
  • 186
sdvnksv
  • 9,350
  • 18
  • 56
  • 108
  • 1
    jQuery struggles reading non-standard CSS properties. Use plain JS instead – Rory McCrossan Aug 26 '18 at 09:53
  • `console.log($(document.body).css('--theme-mode')` does return `dark`. – sdvnksv Aug 26 '18 at 09:54
  • This is not a duplicate because the line above does return the string. However, it retuns false when I try to compare the strings. – sdvnksv Aug 26 '18 at 09:55
  • 2
    because return string value is ' dark' try following code `alert(themeMode == ' dark');` – Ahmed Yousif Aug 26 '18 at 09:55
  • @AhmedYousif. Bravo! Thanks for your help. Shame on others who try to mark it as a duplicate without trying to understand the issue. – sdvnksv Aug 26 '18 at 09:56
  • @sdvnksv no, it returns `undefined` as you'll see when you try this in Chrome in the edit I made to your snippet. As my first comment said, jQuery cannot reliably retrieve made-up CSS properties in a cross browser safe way. You *need* to use plain JS if you want this to work reliably. – Rory McCrossan Aug 26 '18 at 10:34
  • @RoryMcCrossan, I use jQuery 3.3.1 and it works just fine in Chrome: https://jsfiddle.net/fwt27b01/1/ – sdvnksv Aug 26 '18 at 21:10
  • Then why did you put jQuery 2.1.1 in the snippet? – Rory McCrossan Aug 26 '18 at 21:29
  • @RoryMcCrossan, because that's the latest available in the SO editor. – sdvnksv Aug 27 '18 at 08:10

0 Answers0