HTML
createElement() 創建元素 document.createElement() 創建一個元素。 例 : document.createElement("div") document.createElement("P") document.createElement("input") .......等等 document.createElement() 可以建立一個新的元素。 document.createTextNode() 就是用來建立文字節點的方法。 document.createDocumentFragment() 一開始我們有一個 HTML 的容器元素。 Node.appendChild() 方法在節點的子節點列表末新增新的子節點。 Node.insertBefore() 方法在節點的子節點列表任意位置插入新的節點。 Node.removeChild() 方法從 DOM 移除一個子節點,並返回移除的節點。 Node.replaceChild() 實現子節點(對像)的替換。返回被替換對像的引用。 Node.hasChildNodes() 取得值,指出這個節點是否有子節點。
<script> function myFunction() { var newDiv = document.createElement("div"); var newContent = document.createTextNode("Hi"); newDiv.appendChild(newContent); document.body.appendChild(newDiv, div1); }
<script> function myFunction() { var newDiv = document.createElement("div"); var newContent = document.createTextNode("Hi"); newDiv.appendChild(newContent); div1.appendChild(newDiv, div1); }
<ul id="myList"> <li>Coffee</li> <li>Tea</li> </ul> <script> function myFunction() { var newNode = document.createElement("li"); var textNode = document.createTextNode("Water"); newNode.appendChild(textNode); myList.insertBefore(newNode, myList.children[1]); } </script>
<input type="button" value="1 remove me" onclick="updateList(this)"> <input type="button" value="2 remove me" onclick="updateList(this)"> <input type="button" value="3 remove me" onclick="updateList(this)"> <input type="button" value="4 remove me" onclick="updateList(this)"> <input type="button" value="5 remove me" onclick="updateList(this)"> <script> function remove(x) { document.body.removeChild(x) } </script>
nodeObject.children 子元素 <div id="Mdiv"> <div> 111 </div> <a> 222 </a> <h1> 333 </h1> <p> 444 </p> </div>
444
nodeObject.parentElement 父元素 <div id="Mdiv"> <div id="div"> 111 <a id="a"> 222 </a> <h1 id="h1"> 333 </h1> </div> <p id="P"> 444 </p> </div>
聚焦:element.focus()獲得焦點 element.blur()失去焦點 <input type="type" value="⇦ blur" onmouseout = "this.blur(); this.value= '⇦ blur'" onmouseover = "this.focus();this.value= '⇦ focus'" /> <style> input:focus {background-color: yellow } input {background-color: lime } </style>
<input type="type" value="⇦ blur" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("input").mouseover(function(){ $("input").focus(); $("input").val("focus"); }); $("input").mouseout(function() { $("input").blur(); $("input").val("blur"); }); }); </script>