Creating a
with javascript createElement?

后端 未结 5 703
终归单人心
终归单人心 2020-12-30 19:41

I need to create a
tag dynamically with javascript.

var br = document.createElement(\'br\');

And

         


        
相关标签:
5条回答
  • 2020-12-30 19:58

    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.

    0 讨论(0)
  • 2020-12-30 19:59

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

     <SCRIPT language="javascript">
        function add() {
    
         //Create an input type dynamically.
            var br = document.createElement("br");
            var foo = document.getElementById("fooBar");
            foo.appendChild(br);
        } 
        </SCRIPT>
    
        <INPUT type="button" value="Add" onclick="add()"/>
        <span id="fooBar">&nbsp;</span>
    
        This text will go down every time you click on add button
    
    0 讨论(0)
  • 2020-12-30 20:00

    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.

    0 讨论(0)
  • 2020-12-30 20:09

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

    0 讨论(0)
  • 2020-12-30 20:12

    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.

    0 讨论(0)
提交回复
热议问题