I want to spawn three random colored div boxes behind each list element. I started with this, however it doesn't work - DIVs don't appear to be visible :(
/
Help much appreciated!
HTML
<div id="wrapper">
<ul>
<li>li1</li>
<li>li2</li>
<li>li3</li>
</ul>
</div>
JS
$("li").each(function(){
var randomColor = "#"+Math.floor(Math.random()*16777215).toString(16);
for (var i = 0; i < 3; i++) {
stripe = document.createElement('div');
stripe.setAttribute('style', 'width:100px; height:3px; background-color' + randomColor);
wrapper = document.getElementById("wrapper");
wrapper.appendChild(stripe);
}
});
I want to spawn three random colored div boxes behind each list element. I started with this, however it doesn't work - DIVs don't appear to be visible :(
http://jsfiddle/dgweu/1/
Help much appreciated!
HTML
<div id="wrapper">
<ul>
<li>li1</li>
<li>li2</li>
<li>li3</li>
</ul>
</div>
JS
$("li").each(function(){
var randomColor = "#"+Math.floor(Math.random()*16777215).toString(16);
for (var i = 0; i < 3; i++) {
stripe = document.createElement('div');
stripe.setAttribute('style', 'width:100px; height:3px; background-color' + randomColor);
wrapper = document.getElementById("wrapper");
wrapper.appendChild(stripe);
}
});
Share
Improve this question
edited Aug 20, 2012 at 20:42
wirey00
33.7k7 gold badges55 silver badges65 bronze badges
asked Aug 20, 2012 at 20:34
user1612686user1612686
1782 silver badges10 bronze badges
4 Answers
Reset to default 5The divs aren't visible because there's a syntax error in your CSS. You're missing a :
after background-color
.
To make the divs appear behind the li
s, you could position the divs absolutely and the li
s relatively.
Have a look at this DEMO. I've also tidied up your JS.
You missed a colon in the javascript after the background-color element. jsFiddle
stripe.setAttribute('style', 'width:100px; height:3px; background-color:' + randomColor);
Your idea is correct, but you have a simple syntax error in your JavaScript.
stripe.setAttribute('style', 'width:100px; height:3px; background-color:' + randomColor);
You simply forgot the colon (:
) after background-color
in the setAttribute()
function.
You're missing a colon after your background-color
another thing, you said you wanted to insert the colored div behind each list element. you're script will just tack the elements at the end
I believe this is what you wanted
http://jsfiddle/dgweu/4/
Use jquery more often, it's incredibly convenient.
jQuery's insertbefore method makes everything easier
You create an element, query it, then insert it before each li element