0

I'm trying to read the background color set by bootstrap in the alert box.

var qc = $(".alert-primary").css("background-color");

This returns undefined. How should I get its value?

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
  • probably a dupe, here you go https://stackoverflow.com/questions/6338217/get-a-css-value-with-javascript – ZzCalvinzZ Apr 20 '18 at 15:12
  • 1
    Working as expected for me. You sure some other code isn't interfering or you're trying to target a class that is loaded outside the DOM without a listener? See: https://www.bootply.com/36vcaTAgHE – Robert Apr 20 '18 at 15:19
  • Working for me, may be you are not including jQuery or using this code before jQuery loads.. – Abhishek Mishra Apr 20 '18 at 15:22
  • make sure there are any element with `alert-primary` class – Anfath Hifans Apr 20 '18 at 15:25

2 Answers2

0

Your doing it perfectly right you can also do as follows:-

$(".alert-primary")[0].style.backgroundColor

or

var qc = $(".alert-primary").css("background-color");

I think your not getting $(".alert-primary") object. Please make sure $(".alert-primary") is getting the correct element, which has background-color.

Sagar Kharche
  • 2,577
  • 2
  • 24
  • 34
0

I found the issue, the selection works only after I 've created a DOM element with that class.

This works:

<div class="alert alert-info">hello</div>
<script>
   var aa = $(".alert-info").css("background-color");
   alert(aa);
</script>

Without the first line, it doesn't work.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78