Skip to content Skip to sidebar Skip to footer

Creating A
With Javascript Createelement?

I need to create a tag dynamically with javascript. var br = document.createElement('br'); And var br = document.createElement(''); doesn't work The firs

Solution 1:

The first method does not need to pass XHTML standards - you're confusing markup with manipulating the DOM.

Solution 2:

A Simple Script of HTML and JavaScript to add br tag dynamically in the page.

<SCRIPTlanguage="javascript">functionadd() {

     //Create an input type dynamically.var br = document.createElement("br");
        var foo = document.getElementById("fooBar");
        foo.appendChild(br);
    } 
    </SCRIPT><INPUTtype="button"value="Add"onclick="add()"/><spanid="fooBar">&nbsp;</span>

    This text will go down every time you click on add button

Solution 3:

The first option will work and has nothing to do with XHTML since the DOM operations are performed after parsing of the document, and therefore there is no XHTML/HTML standard to be compliant to at that point. As long as you are not trying to output the HTML to a string, this approach will work just fine.

Solution 4:

This question has nothing whatever to do with markup. The argument passed to createElement is an element name, it is not a fragment of markup or anything else, it isn't XML, or HTML, or XHTML, or SGML or any form of markup.

The createElement method returns a DOM object, there is no markup and never was.

Note that the markup passed to the browser is used to create a document object, from that point onward, the markup is irrelevant.

Solution 5:

In reality, your code will still validate if your JavaScript doesn't exactly validate, because the validator only parses the processed HTML code, not the dynamic code created by JavaScript. If you cared, you could also use an innerHTML trick, or a document.createTextNode('<br />'); if you wanted to force the XHTML version, but it is not recommended. document.createElement('br'); works perfectly fine.

Post a Comment for "Creating A
With Javascript Createelement?"