This article brings you relevant knowledge about javascript, which mainly introduces the relevant content about obtaining elements and nodes, including obtaining elements through id, class name, name, and tag name. , creating, deleting, cloning nodes and other issues, let’s take a look at them together, I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end】
// 1 获取元素节点 // 通过id的方式( 通过id查找元素,大小写敏感,如果有多个id只找到第一个) document.getElementById('p1');
// 通过类名查找元素,多个类名用空格分隔,得到一个HTMLCollection(一个元素集合,有length属性,可以通过索引号访问里面的某一个元素) var cls = document.getElementsByClassName('a b'); console.log(cls);
// 通过name属性查找,返回一个NodeList(一个节点集合,有length属性,可以通过索引号访问) var nm = document.getElementsByName('c'); console.log(nm);
// 通过标签名查找元素 返回一个HTMLCollection document.getElementsByTagName('p');
document.querySelector('.animated')
document.querySelector('.animated')
In the Document Object Model (DOM), each node is an object. DOM nodes have three important attributes
1. nodeName: the name of the node
2. nodeValue: the name of the node Value
3. nodeType: The type of node
1. nodeName attribute: The name of the node, It is read-only.
2. nodeValue attribute: the value of the node
3. nodeType attribute: the type of node, It is read-only. The following commonly used node types:
1. Create node: createElement('')
// 创建元素,只是创建出来并未添加到html中,需要与appendChild 配合使用 var elem = document.createElement('p'); elem.id = 'test'; elem.style = 'color: red'; elem.innerHTML = '我是新创建的节点'; document.body.appendChild(elem);
2. Insert node: appendChild ()
var oNewp=document.createElement("p"); var oText=document.createTextNode("World Hello"); oNewp.appendChild(oText);
2-1. Insert node: insertBefore()
var oOldp=document.body.getElementsByTagName("p")[0]; document.body.insertBefore(oNewp,oOldp);
1.删除节点:removeChild
var op=document.body.getElementsByTagName("p")[0]; op.parentNode.removeChild(op);
1.克隆节点:parent.cloneNode() false 或者true
// 克隆节点(需要接受一个参数来表示是否复制元素) var form = document.getElementById('test'); var clone = form.cloneNode(true); clone.id = 'test2'; document.body.appendChild(clone);
1.替换节点 方法node.replace(new,old)
var oOldp=document.body.getElementsByTagName("p")[0]; oOldp.parentNode.replaceChild(oNewp,oOldp);
(function() { var start = Date.now(); var str = '', li; var ul = document.getElementById('ul'); var fragment = document.createDocumentFragment(); for(var i=0; i<10000; i++) { li = document.createElement('li'); li.textContent = '第'+i+'个子节点'; fragment.appendChild(li); } ul.appendChild(fragment); console.log('耗时:'+(Date.now()-start)+'毫秒'); // 63毫秒 })();
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of JavaScript knowledge points collection: obtaining elements and nodes. For more information, please follow other related articles on the PHP Chinese website!