Domanda

I write some code to make a progressbar. But when i run the code on line 30 there comes a error:

  • ReferenceError: einfuegen2 is not defined
  • zielort.appendChild(einfuegen2)

I'm really confused what I should do. Can anyone help me with my problem?

JS Code:

function progress(){

        var min = 0;
        var max = 10;
        var x = Math.floor(Math.random() * (max - min)) + min;


        for(var i = 0; i < x; i++){


            var einfuegen = document.createElement('div');
            einfuegen.className = 'statusbar';

            document.body.appendChild(einfuegen);   

            var einfuegen2 = document.createElement('img');
            einfuegen2.id = 'bild';
            einfuegen2.name = 'bild';
            einfuegen2.src = 'project_status.gif';


            var zielort = document.getElementsByClassName('statusbar');
            zielort.appendChild(einfuegen2);

        }       
}

HTML CODE:

<input name="Progress" type="button" onclick="progress()" value="Progress!" />
<div class="statusbar">
    <img id="bild" name="bild" src="project_status.gif"/>
</div>
È stato utile?

Soluzione 3

This can't work, because getElementsByClassName (see the plural in the name) does return a collection of elements (a little bit like an array), even if it finds only one element.

But the whole part is redundant, since you created the element from script just a few lines ago and stored it in "var einfuegen".

just use

einfuegen.appendChild(einfuegen2);

Altri suggerimenti

getElementsByClassName Returns an array of elements. Try this.

var zielort = document.getElementsByClassName('statusbar')[0];
zielort.appendChild(einfuegen2);

It doesnt know where to append the child element to the array object...

This will append it to the beginning (index 0 ):

        var zielort = document.getElementsByClassName('statusbar');
        zielort[0].appendChild(einfuegen2);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top