【DOM编程艺术】动态创建标记(签)---创建和插入节点

window.onload=function(){
    var para=document.createElement('p');
    var info= 'nodeName:';
    info += para.nodeName;
    info += '  nodeType:';
    info += para.nodeType;
    alert(info);    //nodeName:P nodeType:1
}

createElement用来创建元素节点

创建P元素后,P元素就像任何其他的节点一样有了自己的DOM属性。即nodeName和nodeType值

window.onload=function(){
    var para=document.createElement('p');
    var testdiv=document.getElementById('testdiv');
    testdiv.appendChild(para);
    alert(testdiv.innerHTML); //<p></p>
}

创建元素,后插入文档中

window.onload=function(){
    var para=document.createElement('p');
    var testdiv=document.getElementById('testdiv');
    testdiv.appendChild(para);
    var txt=document.createTextNode('Hello world!');
    para.appendChild(txt);
    alert(testdiv.innerHTML); //<p>Hello world!</p>
}

以上例子是按照以下顺序来创建和插入节点的:

(1)创建一个p元素

(2)将p元素插入到文档的一个元素节点上

(3)创建一个文本节点

(4)将文本节点插入到刚才创建的p元素节点上

转载于:https://www.cnblogs.com/positive/p/3665475.html

猜你喜欢

转载自blog.csdn.net/weixin_33859665/article/details/93495761