David David - 4 months ago 9
CSS Question

Setting rgba on string element

I'm trying to create an element and change the background color before adding the element to the page.

This is my approach:

var element = '<div>content</div>';
$(element).css('background-color', 'rgba(255,255,255,0.5)');​

I'm always getting an
Uncaught SyntaxError

Is there a better approach for my problem?

There are two problems. The first one is an invisible character in line 2, after the ;. The second one is that I need to create at first the DOM Element before modifying the element.


The cause of your syntax error is an invisible character ​at the end of your second line.

You can detect such hidden characters by copy-pasting your code into JsFiddle :

enter image description here

Remove the character to solve your syntax error.

To achieve what you're going for, you'll also need to put your '<div>content</div>' between $() :

var element = $('<div>content</div>');
$(element).css('background-color', 'rgba(255,255,255,0.5)');

See this Fiddle for a working demo!