您的位置:首页 > Web前端 > JavaScript

Javascript DOM 的节点操作示例

2015-05-08 17:27 513 查看
CODE:

<body>

<div>

<divid="one"style="width:300px;height:110px;border:1pxsolidblack;margin-top:15px">

<p>第一个元素</p>

<p>第二个元素</p>

</div>

<ahref="javascript:append()">直接追加</a>


<divid="two"style="width:300px;height:110px;border:1pxsolidred;margin-top:15px">

<p>第一个元素</p>

<p>第二个元素</p>

</div>

<ahref="javascript:insert()">之前追加</a>


<divid="three"style="width:300px;height:110px;border:1pxsolidgreen;margin-top:15px">

<p>第一个元素</p>

<p>第二个元素</p>

</div>

<ahref="javascript:insertAfter()">之后追加</a>

</div>


<script>

functioncreateObj(){

varimg=document.createElement("img");

img.src="lang.gif"

img.style.width="50px";

img.style.height="50px";

returnimg;

}



functionappend(){

varone=document.getElementById("one");

varimg=createObj();

one.appendChild(img);

}


functioninsert(){//这个方法要求对象必须是目标对象的父级元素!!!

vartwo=document.getElementById("two");

varobj=document.getElementById("two").getElementsByTagName("p")[0];

varimg=createObj();

two.insertBefore(img,obj);

}


functioninsertAfter(){//没有在元素之后插入的方法,可手动创建加以合适的判断

varthree=document.getElementById("three");

varobj=document.getElementById("three").getElementsByTagName("p")[0];

varimg=createObj();

if(obj.nextSibling)

three.insertBefore(img,obj.nextSibling);

else

three.appendChild(img);

}


</script>

</body>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: