简体   繁体   中英

I generated html code (lots of divs) with javascript. Now I want to find the generated divs with GetElementById

GetElementById works if I manually added a div id="something" inside the body and use window.onload = init method in the script to get it. Works great.

But if I used a for loop to generate divs where id's is 1,2,3 and so on. I can't get it. Is there a way to get to those generated divs?

This is what generates the html code (just to be clear what I mean):

for(i=0; i<randomizeColoursList.length; i++)
{
    document.getElementById("renderColors").innerHTML += 
        '<div class=\"box\"><div class=\"' + i + '\"><font color=\"' 
        + randomizeColoursList[i] + '\">' 
        + "" + '<img src=\"dist/card_bg.gif\"></div></div>';                    
}   

Generates one of these:

<div class="8"><font color="#3be6c4"><img src="dist/card_bg.gif"></font></div>

Div with class 8 is the id I want to get for example. But is says it's null.

Thanks.

The id is null because you haven't specified it in your markup creation. Looks like you're assigning the id value to class instead.

Generate something more like this:

<div id="div1" class="8"><font color="#3be6c4"><img src="dist/card_bg.gif"></font></div> 

Also, you don't need to use font tags, nor should you use them. Just add the styling to the div.

<div id="div1" class="8" style="color:#3be6c4;"><img src="dist/card_bg.gif"></div> 

The way you're going about this is a little backwards. If you write your code like I have below, then you don't need to give the divs IDs, you end up with an array full of references to them anyway.

var i, div, img;
var createdDivs = [];
for(i=0; i<randomizeColoursList.length; i++)
{
    div = document.createElement('div');
    img = document.createElement('img');
    div.className = "box";
    div.style.backgroundColor = randomizeColoursList[i];
    div.style.color = randomizeColoursList[i];
    img.src = "dist/card_bg.gif"

    div.appendChild(img);
    document.getElementById("renderColours").appendChild(div);                

    createdDivs.push(div);
}  

Live link: http://jsfiddle.net/7HjLL/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM