JPashs
JPashs

Reputation: 13886

Jquery and hex colors?

I can't set a color if I retrieve the hex code color from a html text. It works fine if I set the color manually.

html

<div class="main-wrapper">
   <div class="html-element-color">#ccff00</div>
   <div class="wrapper">hello</div>
</div>
<div class="main-wrapper">
   <div class="html-element-color">#cccccc</div>
   <div class="wrapper">hello</div>
</div>
<div class="main-wrapper">
   <div class="html-element-color">#f1f1f1</div>
   <div class="wrapper">hello</div>
</div>

This code works fine

$( ".html-element-color" ).each(function( index ) {

  var bgColorWrapper = "#ccff00";

   $(this).parent().find("div.wrapper").css( "background-color", bgColorWrapper ) ;

})

;

Here the code which doesn't work:

$( ".html-element-color" ).each(function( index ) {

  var bgColorWrapper = $('.html-element-color').text();

   $(this).parent().find("div.wrapper").css( "background-color", bgColorWrapper ) ;

});

Upvotes: 0

Views: 208

Answers (1)

Blaise
Blaise

Reputation: 13479

bg-color is an invalid variable name. Variable names cannot contain dashes. Try this instead.

$( ".html-element-color" ).each(function( index ) {

  var bgColor = $('.html-element-color').text();

   $(this).parent().find("div.wrapper").css( "background-color", bgColor ) ;

});

Also, it is likely that you want to set the color from the same element, but your intention is unclear from your post. Maybe this is what you actually want:

$( ".html-element-color" ).each(function( index ) {

  var bgColor = $(this).text();

   $(this).parent().find("div.wrapper").css( "background-color", bgColor ) ;

});

Upvotes: 3

Related Questions