javascript - DOM gets the difference between elements with or without quotes when creating and inserting
阿神
阿神 2017-06-14 10:53:37
0
5
726

<!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>
阿神
阿神

闭关修行中......

reply all(5)
三叔

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.

滿天的星座

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');
某草草

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

伊谢尔伦

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

曾经蜡笔没有小新
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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template