本文向大家介绍一下如何使用JavaScript创建div节点元素,主要包括创建div节点元素的属性和创建div节点元素的样式两大部分内容,相信本文介绍一定会让你有所收获。
JavaScript创建div的属性和样式
问题域:
如何由JavaScript创建div节点元素:
◆创建div节点元素的属性;
◆创建div节点元素的样式;
解决方案:
1、创建div元素:
Javascript代码
<script type=”text/javascript”>
function createElement(){
var createDiv = document.createElement(“div”);
createDiv.innerHTML = “Test create a div element!”;
document.body.appendChild(createDiv);
}
</script>
2、创建div的属性:
Javascript代码
<script type=”text/javascript”>
function createElement(){
var createDiv = document.createElement(“div”);
createDiv.title=”this is a new div.”;
createDiv.id=”newDivId”;
createDiv.class = “newDivClass”;
createDiv.innerHTML = “Test create a div element!”;
document.body.appendChild(createDiv);
}
</script>
3、创建div的样式:
Javascript代码
<script type=”text/javascript”>
function createElement(){
var createDiv = document.createElement(“div”);
createDiv.style.background = “pink”;
createDiv.style.border=”1px solid red”;
createDiv.style.width = “50px”;
createDiv.style.height = “50px”;
createDiv.innerHTML = “Test create a div element!”;
document.body.appendChild(createDiv);
}
</script>
4、删除或隐藏DIV
Javascript代码
<script type=”text/javascript”>
function removediv(DivId){
var div = document.getElementByIdx(DivId);
div.style.display = “none”; //隐藏而不删除
div.parentNode.removeChild(div); //删除
}
</script>
评论