Question

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);
Was it helpful?

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

OTHER TIPS

As described by Carlo in another answer, you cannot use the jQuery selector to select elements that haven't been added. You can however, turn a created DOM element into a jQuery object by doing:

var thecolor2 = $(document.createElement('div'));

However, if you're going to be using jQuery then I suggest writing everything in jQuery, otherwise stick with using pure JavaScript for everything.

jQuery

var thestream = $('#allposts');
var oneofpost = $('<li></li>');
var thecolor2 = $('<div></div>');
thecolor2.prop('id', "thecolor2")
         .css({
             backgroundColor: color
         }).appendTo(oneofpost);
thestream.append(oneofpost);

See jsFiddle

JavaScript

var thestream = document.getElementById('allposts');
var oneofpost = document.createElement('li');
var thecolor2 = document.createElement('div');
thecolor2.id = "thecolor2";
thecolor2.style.backgroundColor = color;
oneofpost.appendChild(thecolor2);
thestream.appendChild(oneofpost);

See jsFiddle

Also I'm assuming you're trying to append a list item to the ul, so I corrected the code you had there with appendChild.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top