1

I'm trying to use the text inside the first div of an element as the CSS color value on a different element. Here's the code I've come up with so far:

<style>
  h1.page-title {
    color: red !important;
  }    
</style>

<div id="field">
  <div style="font-size:0;">#666!important</div>
  <div style="font-size:0;">second div</div>
</div>

<h1 class="page-title">hello</h1>

<script>
$(function() {
  var x = $("#field div:first").text();
  $("h1.page-title").css("color", x);
});
</script>

So far the Javascript/jQuery code doesn't seem to be working for me, but I don't know why. Is there any way to accomplish this? Please keep in mind that modifying the HTML code in any way wouldn't be ideal.

Many thanks in advance.

C.L.
  • 13
  • 2

1 Answers1

0

You can't pass "!important" to JQuery's CSS (or at least, not like that). Drop that and it works.

You could:

a. Change it to something like $("h1.page-title").css('cssText', 'color:' + x); ("cssText" will add what you pass as a string.) – or see some of the other answers to "how to apply '!important' in jQuery" linked below.

b. Don't use !important if possible. There's really no reason you should have an inline important, unless the CSS having an important is completely out of your control.


Using !important in jQuery's css() function

How to apply !important using .css()?

SamVK
  • 3,077
  • 1
  • 14
  • 19