Sunday 15 February 2015

How to write unclosed HTML statements with JavaScript -



How to write unclosed HTML statements with JavaScript -

in writing javascript project, i've run problem. need create couple of div elements, clone selection list , close divs. using innerhtml has side-effect of automatically closing "open" html statements left hanging. here's example:

<html><head></head><body> <div id="mydiv"></div> <script> var mydiv = document.getelementbyid("mydiv"); mydiv.innerhtml = mydiv.innerhtml + '<i>this should <b>bold '; mydiv.innerhtml = mydiv.innerhtml + '</b> , should not</i>'; </script> </body></html>

when executed browser, italic , bold first innerhtml assignment automatically "closed" me. can maintain them open?

since seem using appendchild other things , need insert dom objects document, should consider like:

var mydiv, span; mydiv = document.getelementbyid("mydiv"); span = document.createelement('span'); span.classname = 'boldclass'; span.appendchild(document.createtextnode('this should bold')); div.appendchild(span); // add together other dom objects here span = document.createelement('span'); span.classname = 'notboldclass'; span.appendchild(document.createtextnode(' , should not')); div.appendchild(span);

you can have function returns dom elements based on passed parameters, e.g.

function makeelement(tagname, props) { var el = document.createelement(tagname); (var p in props) { if (props.hasownproperty(p)) { el[p] = props[p]; } } homecoming el; }

so can things like:

span = makeelement('span', {classname: 'boldclass'});

note there few quirks deal research , test thoroughly.

javascript html

No comments:

Post a Comment