0

I'm using jQuery to check if a particular CSS property and value exist. Why doesn't it work? I'm expecting to see the 'yes' log.

$(document).ready(function() {
  if ($('p').css('color') === 'blue') {
    console.log('yes');
  } else {
    console.log('no');
  }
});
p {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>text</p>

1
  • Your color is coming back as RGB, hence checking for blue won't work. Commented Apr 17, 2017 at 19:28

2 Answers 2

2

Your color is coming back as an RGB value, not the name of the color. You'll want to do a comparison against the RGB string instead.

$(document).ready(function() {
var color = $('p').css('color');
console.log(color);
if (color === 'rgb(0, 0, 255)') {
    console.log('yes');
  } else {
    console.log('no');
  }
});
p {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>text</p>

Sign up to request clarification or add additional context in comments.

Comments

1

You can iterate document.styleSheets, check if cssRules .selectorText is equal to "p", then check if .style .color property is equal to "blue"

$(document).ready(function() {
  for (let {cssRules: [{selectorText, style:{color}}]} of document.styleSheets) {
    if (selectorText === "p") {
      if (color === "blue") {
        console.log("yes")
      } else {
        console.log("no")
      }
      break;
    }
  }
});
p {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>text</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.