Search code examples
javascripthtmlcssappendchild

Add css before appending child


So I have a div (with the id of "thecolor2") that I want to append to an unordered list, but before I append it, I want to set its background color to a variable which has the value of a hex code. However, for some reason, it doesn't take in the color.

Here is the CSS:

#thecolor2{
    height: 50px;
    width: 50px;
    border-radius: 100px;
    border: 1px solid yellow;
    position: relative;
    bottom: 635px;
}

Her is the HTML:

<ul id = "allposts"></ul>

And here is the JS:

var thestream = document.getElementById('allposts');
var oneofpost = document.createElement('li');
var thecolor2 = document.createElement('div');
thecolor2.id = "thecolor2";
$("#thecolor2").css("background-color", color);
thestream.appendChild(oneofpost);
thestream.appendChild(thecolor2);

Solution

  • You cant use a jQuery ID selector to match a node which hasn't been added to the document tree. You can simply use plain DOM to set its inline CSS style like this:

    thecolor2.style.backgroundColor = color