Dynamic Web Pages Using JavaScript Accessing and Manipulating HTML Elements
Manipulating HTML elements (2)
It is not only possible to access HTML elements,
but also possible to add new ones and remove old ones on-the-fly
<html >< head > < title > Manip u l ating HTM L ele ment s (2) </ title > </ head >
<body >< ta ble bor der ="1" > < tr >
<td oncli ck =" add Left ( this );" > add </ td >
<td oncli ck =" remov e Left ( this . paren t Node );" > remove </ td >
</tr > </ table > < script >
fu n ctio n addL eft ( n ode ) {
// Maint a in a counter that is i ncreme n ted with each call
ad dLef t . coun ter = addL eft . co unte r || 0;
ad dLef t . coun ter ++;
// Crea te a new TD el emen t with coun ter as con tent
newTD = docume nt . create E l ement (' td ' );
newTD . i nnerH TML = addL eft . co unte r ;
newTD . s e tAttri b u te ( ' id ' , add Left . c ount er );
// Add the new TD elem ent befor e the curr ent one
node . p arent N ode . insert B efore ( newTD , node );
}
fu n ctio n r emove L eft ( parent ) {
pa rent . r emoveC h ild ( parent . f i rstCh i ld );
}
</ script > </ body > </ html >
http://cgi.csc.liv.ac.uk/
~
ullrich/COMP519/examples/jsTD.html
COMP519 Web Programming Lecture 17 Slide L17 – 9