DOM Tip

admin

Administrator
Staff member
The attachChild method of the node object returns the added node. This allows to add a number of nested nodes with one line of javascript code without the need of extra variables to store nodes.
For example adding a paragraph with a text to the document body:

document.body.appendChild(document.createElement('p')).appendChild(document.createTextNode('paragrap h text'));

Adding the power of with statement you can construct a complete node tree without a single variable declaration:

with(document.body.appendChild(document.createElement('div')))
{ appendChild(document.createElement('p')).appendChild(document.createTextNode('first paragraph'));
appendChild(document.createElement('p')).appendChild(document.createTextNode('second paragraph'));
with(style)
{ background="#00ee00";
padding="20px";
}
with(appendChild(document.createElement('div')))
{ appendChild(document.createElement('p')).appendChild(document.createTextNode('third paragraph (child of second div)'));
appendChild(document.createElement('p')).appendChild(document.createTextNode('fourth paragraph (child of second div)'));
with(style)
{ background="#ee0000";
padding="10px";
}
}
}
 
Back
Top