자바 스크립트 : 페이지의 모든 DOM 요소를 반복하는 방법은 무엇입니까?
페이지의 모든 요소를 반복하려고 하므로이 페이지에있는 모든 요소에서 특수 클래스를 확인하고 싶습니다.
그래서 모든 요소를 확인하고 싶다고 어떻게 말합니까?
a *
를 전달 getElementsByTagName()
하여 페이지의 모든 요소를 반환 할 수 있습니다 .
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
// Do something with the element here
}
사용 querySelectorAll()
가능한 경우 (IE9 +, IE8의 CSS)을 사용하여 특정 클래스의 요소를 찾을 수 있습니다.
if (document.querySelectorAll)
var clsElements = document.querySelectorAll(".mySpeshalClass");
else
// loop through all elements instead
이것은 최신 브라우저의 문제를 확실히 가속화시킵니다.
브라우저는 이제 NodeList에서 foreach를 지원 합니다. 즉, 자신 만의 for 루프를 작성하는 대신 요소를 직접 반복 할 수 있습니다.
document.querySelectorAll('*').forEach(function(node) {
// Do whatever you want with the node object.
});
성능 참고 사항 -원하는 내용의 범위를 정하기 위해 최선을 다하십시오. 범용 선택기는 페이지의 복잡성에 따라 많은 노드를 반환 할 수 있습니다. 다른 사람이 볼 수있는 모든 것을 살펴 봐야하더라도
'body *'
선택기로 사용 하여 모든head
내용 을 잘라낼 수 있습니다 .
같은 것을 찾고 있었다. 정확히는 아닙니다. 모든 DOM 노드 만 나열하고 싶었습니다.
var currentNode,
ni = document.createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT);
while(currentNode = ni.nextNode()) {
console.log(currentNode.nodeName);
}
특정 클래스의 요소를 얻으려면 필터 함수를 사용할 수 있습니다.
var currentNode,
ni = document.createNodeIterator(
document.documentElement,
NodeFilter.SHOW_ELEMENT,
function(node){
return node.classList.contains('toggleable') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
);
while(currentNode = ni.nextNode()) {
console.log(currentNode.nodeName);
}
MDN 에서 찾은 솔루션
다음은 문서 나 요소를 반복하는 방법에 대한 다른 예입니다.
function getNodeList(elem){
var l=new Array(elem),c=1,ret=new Array();
//This first loop will loop until the count var is stable//
for(var r=0;r<c;r++){
//This loop will loop thru the child element list//
for(var z=0;z<l[r].childNodes.length;z++){
//Push the element to the return array.
ret.push(l[r].childNodes[z]);
if(l[r].childNodes[z].childNodes[0]){
l.push(l[r].childNodes[z]);c++;
}//IF
}//FOR
}//FOR
return ret;
}
항상 가장 좋은 해결책은 재귀를 사용하는 것입니다.
loop(document);
function loop(node){
// do some thing with the node here
var nodes = node.childNodes;
for (var i = 0; i <nodes.length; i++){
if(!nodes[i]){
continue;
}
if(nodes[i].childNodes.length > 0){
loop(nodes[i]);
}
}
Unlike other suggestions, this solution does not require you to create an array for all the nodes, so its more light on the memory. More importantly, it finds more results. I am not sure what those results are, but when testing on chrome it finds about 50% more nodes compared to document.getElementsByTagName("*");
For those who are using Jquery
$("*").each(function(i,e){console.log(i+' '+e)});
from this link
javascript reference
<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
function findhead1()
{
var tag, tags;
// or you can use var allElem=document.all; and loop on it
tags = "The tags in the page are:"
for(i = 0; i < document.all.length; i++)
{
tag = document.all(i).tagName;
tags = tags + "\r" + tag;
}
document.write(tags);
}
// -->
</script>
</head>
<body onload="findhead1()">
<h1>Heading One</h1>
</body>
</html>
UPDATE:EDIT
since my last answer i found better simpler solution
function search(tableEvent)
{
clearResults()
document.getElementById('loading').style.display = 'block';
var params = 'formAction=SearchStocks';
var elemArray = document.mainForm.elements;
for (var i = 0; i < elemArray.length;i++)
{
var element = elemArray[i];
var elementName= element.name;
if(elementName=='formAction')
continue;
params += '&' + elementName+'='+ encodeURIComponent(element.value);
}
params += '&tableEvent=' + tableEvent;
createXmlHttpObject();
sendRequestPost(http_request,'Controller',false,params);
prepareUpdateTableContents();//function js to handle the response out of scope for this question
}
Andy E. gave a good answer.
I would add, if you feel to select all the childs in some special selector (this need happened to me recently), you can apply the method "getElementsByTagName()" on any DOM object you want.
For an example, I needed to just parse "visual" part of the web page, so I just made this
var visualDomElts = document.body.getElementsByTagName('*');
This will never take in consideration the head part.
Use *
var allElem = document.getElementsByTagName("*");
for (var i = 0; i < allElem.length; i++) {
// Do something with all element here
}
You can try with document.getElementsByClassName('special_class');
'Programing' 카테고리의 다른 글
.net의 거래 (0) | 2020.06.20 |
---|---|
IIS7에서 폴더 및 확장마다 정적 콘텐츠 캐시를 구성하는 방법은 무엇입니까? (0) | 2020.06.20 |
jquery는 클래스와 가장 가까운 이전 형제를 찾습니다. (0) | 2020.06.20 |
파이썬 2.7 사용자 입력 받기 및 따옴표없이 문자열로 조작 (0) | 2020.06.20 |
github (시간 / 일)의“실제”커밋 날짜 참조 (0) | 2020.06.20 |