DOM笔记
问元素方法:
document.getElementById('id')
document.getElementsByTagName('tagname')
document.getElementsByClassName('class')
节点操作方法:
appendChild()
removeChild()
replaceChild()
insertBefore()
reateElement('p')
createAttribute('attribute')
createTextNode('text')
getAttribute(attribute)
setAttribute(attribute)
不要跨代操作
常用的 HTML DOM 属性:
innerHTML - 节点(元素)的文本值
parentNode - 节点(元素)的父节点
childNodes - 节点(元素)的子节点
attributes - 节点(元素)的属性节点
<div id="parents">
<p id="first"> hello world</p>
<p id="second">good bye </p>
<input value="ok">
</div>
var parents = document.getElementById('parents')
1创建元素
var newChild = document.createElement('p')
var newText = document.createTextNode('see you again')
newChild.appendChild(newText)
parents.appendChild(newChild)
2删除元素
var second = document.getElementsByTagName('p')[1]
parents.removeChild(second)
3替换文本
var newText = document.createTextNode('new paragraph')
var oldChild = document.getElementById('first')
oldchild.replaceChild(newText,oldChild.childNodes[0])
4插入元素
var newChild = document.createElement('p')
var newText = document.createTextNode('hahaha')
newChild.append(newText)
parents.insertBefore(newChild,parents.childNodes[0])
parents.insertBefore(newChild,parents.childNodes[1])
5创建属性
var newAtt = document.createAttribute('style')
newAtt.value = "color:red"
var child = document.getElementById('first')
child.setAttributeNode(newAtt)
6返回属性
var child = document.getElementById('first')
var value = child.getAttribute('id')
alert(value)
7设置属性
document.getElementsByTagName('input')[0].setAttribute('type','button');