programing tip

getElementsByClassName을 올바르게 반복하는 방법

itbloger 2020. 10. 21. 07:45
반응형

getElementsByClassName을 올바르게 반복하는 방법


저는 자바 스크립트 초보자입니다.

을 통해 웹 페이지를 초기화 window.onload하고 있으며 클래스 이름 ( slide)으로 여러 요소를 찾아서 일부 논리에 따라 다른 노드에 재배포해야합니다. Distribute(element)요소를 입력으로 사용하고 배포를 수행하는 기능 이 있습니다. (예를 들어 여기 또는 여기에 설명 된대로) 다음과 같이하고 싶습니다 .

var slides = getElementsByClassName("slide");
for(var i = 0; i < slides.length; i++)
{
   Distribute(slides[i]);
}

그러나 이것은 getElementsByClassName실제로 배열을 반환하지 않기 때문에 마술을 하지 않습니다 NodeList.

... 이것은 내 추측입니다 ...

... 함수 내에서 변경됨 Distribute(DOM 트리가이 함수 내에서 변경되고 특정 노드의 복제가 발생 함). For-each루프 구조도 도움이되지 않습니다.

가변 슬라이드는 실제로 비 결정적으로 작동하며 모든 반복을 통해 요소의 길이와 순서를 크게 변경합니다.

내 경우 NodeList를 반복하는 올바른 방법은 무엇입니까? 임시 배열을 채우려 고 생각했지만 어떻게해야할지 모르겠습니다 ...

편집하다:

내가 언급하는 것을 잊은 중요한 사실은 다른 슬라이드 안에 하나의 슬라이드가있을 수 있다는 것입니다. 이것은 실제로 slides사용자 Alohci 덕분에 방금 알게 된 변수를 변경합니다 .

나를위한 해결책은 먼저 각 요소를 배열에 복제하고 배열을 Distribute()나중에 하나씩 전달하는 것이 었습니다 .


MDN에 따르면 a에서 항목을 검색하는 방법 NodeList은 다음과 같습니다.

nodeItem = nodeList.item(index)

그러므로:

var slides = document.getElementsByClassName("slide");
for(var i = 0; i < slides.length; i++)
{
   Distribute(slides.item(i));
}

나는 이것을 직접 시도하지 않았지만 (일반적인 for루프는 항상 나를 위해 일했습니다), 시도해보십시오 .


새로운 querySelectorAll을 사용하면 forEach를 직접 호출 할 수 있습니다.

document.querySelectorAll('.edit').forEach(function(button) {
    // Now do something with my button
});

아래 댓글에 따라. nodeList에는 forEach 함수가 없습니다.

이것을 babel과 함께 사용하면 추가 할 수 있으며 Array.from비 노드 목록을 forEach 배열로 변환합니다. Array.fromIE 11을 포함한 아래의 브라우저에서는 기본적으로 작동하지 않습니다.

Array.from(document.querySelectorAll('.edit')).forEach(function(button) {
    // Now do something with my button
});

지난 밤 모임에서 forEach가없는 노드 목록을 처리하는 다른 방법을 발견했습니다.

[...document.querySelectorAll('.edit')].forEach(function(button) {
    // Now do something with my button
});

브라우저 지원 [...]

노드 목록으로 표시

노드 목록으로 표시

배열로 표시

배열로 표시


항상 배열 메서드를 사용할 수 있습니다.

var slides = getElementsByClassName("slide");
Array.prototype.forEach.call(slides, function(slide, index) {
    Distribute(slides.item(index));
});

나는 그것이 라이브이기 때문에 반대로 반복하는 Alohci 의 권고를 따랐다 nodeList. 궁금한 분들을 위해 제가 한 일입니다 ...

  var activeObjects = documents.getElementsByClassName('active'); // a live nodeList

  //Use a reverse-loop because the array is an active NodeList
  while(activeObjects.length > 0) {
    var lastElem = activePaths[activePaths.length-1]; //select the last element

    //Remove the 'active' class from the element.  
    //This will automatically update the nodeList's length too.
    var className = lastElem.getAttribute('class').replace('active','');
    lastElem.setAttribute('class', className);
  }

 <!--something like this--> 
<html>
<body>



<!-- i've used for loop...this pointer takes current element to apply a 
 particular change on it ...other elements take change by else condition 
-->  


<div class="classname" onclick="myFunction(this);">first</div>  
<div class="classname" onclick="myFunction(this);">second</div>


<script>
function myFunction(p) {
 var x = document.getElementsByClassName("classname");
 var i;
 for (i = 0; i < x.length; i++) {
    if(x[i] == p)
    {
x[i].style.background="blue";
    }
    else{
x[i].style.background="red";
    }
}
}


</script>
<!--this script will only work for a class with onclick event but if u want 
to use all class of same name then u can use querySelectorAll() ...-->




var variable_name=document.querySelectorAll('.classname');
for(var i=0;i<variable_name.length;i++){
variable_name[i].(--your option--);
}



 <!--if u like to divide it on some logic apply it inside this for loop 
 using your nodelist-->

</body>
</html>

참고 URL : https://stackoverflow.com/questions/15843581/how-to-correctly-iterate-through-getelementsbyclassname

반응형