DOM-BOM-EVENT(4)

17385 ワード

4.dom操作
createElementは元素を作成します.
<button id="btn">  </button>
<ul id="ul1"></ul>
<script>
    var oBtn = document.getElementById("btn")
    var oUl = document.getElementById("ul1")
    oBtn.onclick = function(){
        var oLi = document.createElement("li")
        oLi.innerHTML = "nodeing.com"
        console.log(oLi)
    } 
</script>
最後にサブ要素を追加します.
<button id="btn">  </button>
<ul id="ul1"></ul>
<script>
    var oBtn = document.getElementById("btn")
    var oUl = document.getElementById("ul1")
    num = 0
    oBtn.onclick = function(){
        num++
        var oLi = document.createElement("li")
        oLi.innerHTML = "nodeing.com" + num
        oUl.appendChild(oLi)
    } 
</script>
insertBefore()は、ある要素の前にサブ要素を挿入します.
<button id="btn">  </button>
<ul id="ul1">
    <li id="first">11111</li>
</ul>
<script>
    var oBtn = document.getElementById("btn")
    var oUl = document.getElementById("ul1")
    var oFirst = document.getElementById("first")
    num = 0
    oBtn.onclick = function(){
        num++
        var oLi = document.createElement("li")
        oLi.innerHTML = "nodeing.com" + num
        oUl.insertBefore(oLi, oFirst)
        oFirst = oLi
    } 
</script>
removeChild()はあるサブ要素を削除します.
<button id="btn">  </button>
<ul id="ul1">
    <li id="first">11111</li>
</ul>
<script>
    var oBtn = document.getElementById("btn")
    var oUl = document.getElementById("ul1")
    var oFirst = document.getElementById("first")
    num = 0
    oBtn.onclick = function(){
        num++
        var oLi = document.createElement("li")
        oLi.innerHTML = "nodeing.com" + num
        oUl.insertBefore(oLi, oFirst)
        oFirst = oLi
    } 
    oUl.onclick = function(ev){
        var ev = ev || event
        this.removeChild(ev.target)
    }
</script>
get Attribute/set Attribute
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            background-color: royalblue
        }
    </style>
</head>
<body>
    <div id="box">nodeing.com</div>
    <script>
        var oBox = document.getElementById("box")
        alert(oBox.getAttribute("id"))
        document.onclick = function(){
            oBox.setAttribute("class", "box")
        }
    </script>
</body>
</html>
⼵参考文献Dcument.create Element()-Web APIインターフェース|MDN