document的高級篇中提供了節點操作的函數,具體包括:獲取節點,改變節點,刪除節點,替換節點,創建節點,添加節點,克隆節點等函數。我們可以利用這些函數動態改變html的節點。
1、JavaScript
<script type="text/javascript">
function test1(){//對個節點的ID相同時候的情況
var myhref = document.getElementById('same');
window.alert(myhref.innerText);
}
function test2() {//輸出節點的值
var hobbies = document.getElementsByName("hobby");
for (var i = 0; i < hobbies.length; i++) {
if (hobbies[i].checked) {
window.alert("你的愛好是:" + hobbies[i].value);
}
}
}
function getN() {//通過標簽獲取標簽對應的值
var myObj = document.getElementsByTagName('input');
for (var i = 0; i < myObj.length; i++) {
window.alert(myObj[i].value);
}
}
function addtags() {//動態添加超鏈接節點<a></a>
//(1)創建元素<a>
var myElement = document.createElement("a")
//(2)給元素添加必要的標示信息
myElement.href = "http://www.sina.com";
myElement.innerText = "連接到新浪";
myElement.style.left = "200px";
myElement.style.top = "300px";
myElement.style.position = "absolute";
//添加到document.body
document.body.appendChild(myElement);
}
var i = 1;
function addinput() {//添加input元素
var myElement = document.createElement('input');
myElement.type = "button";
myElement.value = "奔跑吧";
//myElement.id="i++";
myElement.id = "id1";
document.getElementById("div1").appendChild(myElement);
}
function deleteinput() {
//刪除一個元素的前提是要知道其父元素是什麼。此方法不是很靈活
//方法一
//document.getElementById("div1").removeChild(document.getElementById('id1'));
//方法二
document.getElementById('id1').parentNode.removeChild(document
.getElementById('id1'));
}
</script>
2.body體中的調用
<body> <a id="same" href="http://www.sohu.com">搜狐</a> <a id="same" href="http://www.baidu.com">百度</a> <a id="same" href="http://www.sina.com">新浪</a> <input type="button" value="提交" onclick="test1()"/> <!-- ID相同的時候只認識第一個 --> <hr/> <input type="checkbox" name="hobby" value="籃球"/>籃球 <input type="checkbox" name="hobby" value="足球"/>足球 <input type="checkbox" name="hobby" value="排球"/>排球 <input type="button" value="提交" name="testing" onclick="test2()"/> <!-- <hr/> <h1>獲取指定標簽的內容</h1> <input type="button" value="智能獲取" onclick="getN()"> --> <hr/> <h1>智能添加標簽</h1> <input type="button" value="智能添加" onclick="addtags()"/> <hr/> <h1>智能添加/刪除input</h1> <div style="width:400px;height:300px;border:3px dashed red;" id="div1"></div> <input type="button" onclick="addinput()" value="inputAdd"/> <input type="button" onclick="deleteinput()" value="inputDelete"/> </body>
以上就是小編為大家帶來的javascript的document中的動態添加標簽實現方法全部內容了,希望大家多多支持~