When the item is in html. In js, we call it this way:

var a = document.getElementByID('label'); 

And if an element is created by a function which is written in js, how to call this element? The function that creates the element:

 function creatElem() { var parent = document.getElementsByTagName('BODY')[0]; var label = document.createElement('label'); label.id = 'label'; } 

The function that needs to call the Label element, which is created by the creatElem() function (which is specified above):

 function label() { var a = (и как переменной "а" присвоить элемент с id = 'label') } 

Apply var a = document.getElementByID('label'); we can not.

Thanks for attention.

    1 answer 1

    Your item is only in memory, so you cannot call it from the document)

    In general:

     function addElement(parent, tag, id) { var el = document.createElement(tag); el.setAttribute('id', id); // хоть убейте, не помню почему, но "очень рекомендуется" parent.appendChild(el); return document.getElementById(id); } 

    This is how it will work.

    Note times: to add a diva to the body of the document, example:

     var myDiv1 = addElement(document.getElementsByTagName('body')[0], 'div', 'mydiv'); 

    Note two: after this div will be available on getElementById .

    Note three, just in case: keep in mind that id must be unique within the document. You can delete an item like this:

     var el = document.getElementById('mydiv'); el.parentNode.removeChild(el); 
    • Sorry I can not throw a plus sign to you, thank you very much. - Afimida
    • So you can accept the answer =) Galku to the left of the answer click) - Sh4dow
    • el.setAttribute ('id', id); // at least kill, I don’t remember why, but "highly recommended" It's very simple - you indicate that the id attribute (name) of the object being created should be equal to the id value that was passed as a parameter to the AddElement function. For example, this could be - label1, label2, etc. - ikot
    • I'm not div.id = id; about that - I don't remember why not " div.id = id; ". Most likely, something is connected with IE, it seems that some attributes simply refuse to assign some attributes. - Sh4dow
    • The function added, now went to function creatElem () {var myDiv1 = addElement (document.getElementsByTagName ('body') [0], 'div', 'mydiv'); } That's right? - Afimida