search

Home  >  Q&A  >  body text

javascript - DOM gets the difference between elements with or without quotes when creating and inserting

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    
    <button id='btn'>创建元素</button>
    
    <script type="text/javascript">
        
        var btn = document.getElementById('btn');
        
        //注册点击事件
        btn.onclick = function(){
            //创建一个元素
            var h1 = document.createElement('h1');
            h1.innerHTML = "这是新增h1标签";

            console.log( h1 );

            //使用appendChild的方式
            //document.body.appendChild( h1 );
            
            //使用insertBefore的方式
            //是在父元素中,先找一个节点,然后插入到它之前
            document.body.insertBefore(h1,btn); //新插入的节点是h1,作为第一个参数
        }

    </script>
</body>
</html>
阿神阿神2799 days ago725

reply all(5)I'll reply

  • 三叔

    三叔2017-06-14 10:55:37

    With quotes it is a string

    var h1 = document.createElement('h1');
        |                            |
        |                            |
        A                            B 
    

    Unquoted are variables:

    document.body.appendChild(h1);
                              |
                              |
                              A
                              
    

    See the document: document.getElementById

    element = document.getElementById(id);

    1. element is an Element object. If the element with the specific ID does not exist in the current document, return null.

    2. id is a case-sensitive string, which represents the unique ID of the element you are looking for.

    h1 is an Element object, 'h1' is a string.

    reply
    0
  • 滿天的星座

    滿天的星座2017-06-14 10:55:37

    It depends on the situation that you are a beginner, so don’t make some confusing variable names. This is your own responsibility. For example:

    var _h1 = document.createElement('h1');

    reply
    0
  • 某草草

    某草草2017-06-14 10:55:37

    When creating a tag, + is used. When inserting, it is equivalent to h1 being a variable. It is not + at this time

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-14 10:55:37

    Without the representative symbol, it is a variable; with the representative symbol, it is a string

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-14 10:55:37

    var h1 = document.createElement('h1');

    h1 in this line is a variable, representing a newly created element. It will be easier to understand if you change the variable name.

    var node = document.createElement('h1');
    document.body.insertBefore(node,btn);

    reply
    0
  • Cancelreply