《中级前端1.8》JavaScript DOM对象控制HTML
获取name,获取元素:
<!-- getElementsByName getElementsTagName --> <p name="pn">Hello</p> <p name="pn">Hello</p> <p name="pn">Hello</p> <p name="pn">Hello</p> <script> function getName() { //两个都是通过集合方式存起来 var count = document.getElementsByName("pn"); var count2 = document.getElementsTagName("p"); alert(count.length); var p = count[0]; p.innerHTML = "World"; } getName(); </script>
获取、设置元素属性:
<!-- 获取,设置属性 --> <a href="#" id="aid" title="得到了a标签的属性">Hello</a> <script> function getAttr() { var anode = document.getElementById("aid"); var attr = anode.getAttribute("title"); var attr2 = anode.getAttribute("id"); document.write(attr); anode.setAttribute("title", "改过了title"); attr = anode.getAttribute("title"); document.write(attr); } getAttr(); </script>
访问子节点:
<!-- 访问子节点,IE9以上会自动给ul li中的空白插入空节点,有兼容问题需要处理后使用 --> <ul><li>1</li><li>2</li><li>3</li></ul> <script> function getChildNode() { var childnode = document.getElementsByTagName("ul")[0].childNodes; alert(childnode.length); } getChildNode(); </script>
访问父节点:
<!-- 访问父节点 --> <div> <p id="pid">div的p元素</p> </div> <script> function getParentNode() { var div = document.getElementById("pid").parentNode; alert(div.nodeName); } getParentNode(); </script>
添加一个节点:
<!-- 添加一个节点 --> <script> function createNode() { var body = document.body; var input = document.createElement("input"); input.type = "button"; input.value = "按钮"; body.appendChild(input); //往末尾加入节点 } createNode(); </script>
往指定位置插入一个节点:
<!-- 插入一个节点 --> <div id="div"> <p id="pid">div的p元素</p> </div> <script> function addNode() { var div = document.getElementById("div"); var node = document.getElementById("pid"); var newnode = document.createElement("p"); newnode.innerHTML = "动态添加一格p元素"; div.insertBefore(newnode, node); } addNode(); </script>
删除节点:
<!-- 删除节点 --> <div id="div"> <p id="pid">div的p元素</p> </div> <script> function removeNode() { var div = document.getElementById("div"); var p = div.removeChild(div.childNodes[1]); } removeNode(); </script>
网页尺寸:
<!-- 网页尺寸 --> <script> function getSize() { var width = document.body.offsetWidth || document.documentElement.offsetWidth; var height = document.body.offsetHeight; alert(width + "," + height); } getSize(); </script>
offsetHeight不包含滚动条的高度, scrollHeight包含滚动条的高度