2017-02-15 1 views
0

어쩌면 다른 사람이 같은 질문을 던졌을 것입니다.하지만 이미 질문에 대한 답이있을 수있는 비슷한 결과를 찾지 못해서 제 질문을 물어볼 것입니다. 나는 살아있는 목록이며, 첫 번째 className 목록이 3 항목에서 2 항목으로 변경됩니다. 그래서 저는 지금 1입니다. 그래서 목록에서 "두 번째 항목"을 건너 뛰었습니다. 라이브 노드 목록의 모든 항목을 루프에 포함시키는 가장 좋은 방법은 무엇입니까? (어쩌면 정적 하나를 사용?)자바 스크립트 라이브 노드리스트 루프

 var hotElements = document.getElementsByClassName("hot"); 
 
     var i; 
 
     var len = hotElements.length; 
 

 
     for (i= 0; i < len ; i++) { 
 
      hotElements[i].className = "pink"; 
 
    }
 .hot { 
 
    background-color: red; 
 
    color: black; 
 
    font-size: 20px; 
 
    weight: 700; 
 
} 
 
.cool { 
 
    background-color: blue; 
 
    font-size: 25px; 
 
} 
 
.pink { 
 
    background-color: pink; 
 
    font-size: 35px;
<h1 id="header"> List King </h1> 
 
<h2> Buy grocceries </h2> 
 
<ul> 
 
    <li id="one" class="hot"> Fresh </li> 
 
    <li id="two" class="hot"> Fresh 1</li> 
 
    <li id="three" class="hot"> Fresh 2 </li> 
 
    <li id="one" class="cool"> Fresh </li> 
 
    <li id="two" class="cool"> Fresh 1</li> 
 
    <li id="three" class="cool"> Fresh 2 </li> 
 
</ul>

+0

단지의 첫 번째 요소의 클래스를 변경 그것은 당신이 그것을 사용하는 경우 요소를 찾을 수 있도록 계속 전달 위에 루프 수, 비 라이브있는 NodeList를 반환 list :'hotElements [0] .className = "pink";'반복하는 동안. 또는 역순으로 반복하거나'querySelectorAll'을 사용하여 정적리스트를 얻습니다. – Teemu

+0

@Teemu 그런 다음'len'과'i' 변수를 제거하고 루프 조건으로'hotElements [0]'을 사용하고 대신'while' 루프를 사용할 수 있습니다. – Xufox

+0

@Xufox Jup, 가능합니다. – Teemu

답변

1

한 가지 방법 뒤로 컬렉션을 통해 루프이며, 그런 식으로 항목이이 위치에 영향을주지 않습니다 제거 된 경우

var hotElements = document.getElementsByClassName("hot"), 
    i; 

for (i = hotElements.length - 1; 0 <= i; i--) { 
    hotElements[i].className = "pink"; 
} 

한가지 장점이 방법의 while(hotElements.length > 0) 용액 0,123 이상 : 나머지 요소 중 어느은 모든 요소에 대해 수행하는 대신 조건부로 새로운 className을 적용하는 경우 제거되는 요소에 의존하지 않는다고 제안했습니다.

실제 노드 컬렉션을 변경할 수없는 실제 배열로 변환 할 수도 있습니다.

spread 구문을 사용하여 수행 할 매우 쉽습니다 ES2015 사용 :

var hotElements = document.getElementsByClassName("hot"); 

[...hotElements].forEach(function (element) { 
    element.className = "pink"; 
}); 

또한 조금 더 코드 ES5에서 작업을 수행 할 수 있습니다

var hotElements = document.getElementsByClassName("hot"); 

Array.prototype.slice.call(hotElements).forEach(function (element) { 
    element.className = "pink"; 
}); 

가로 변환 slice 사용을 배열은 IE < 9에서 작동하지 않습니다 ...하지만이 시점에서 아마 우려하지 않습니다.

또 다른 방법은 querySelectorAll을 사용하는 것입니다.

var hotElements = document.querySelectorAll(".hot"), 
    i, 
    len = hotElements.length; 

for (i = 0; i < len ; i++) { 
    hotElements[i].className = "pink"; 
} 

재미있는 관련 기사 : A comprehensive dive into NodeLists, Arrays, converting NodeLists and understanding the DOM

+1

위대한 대답은 첫 번째 방법에서 단 하나의 작은 실수입니다. for 루프에서 hotItems.length -1을 수행해야합니다. –

+0

@ChristodoulouAndreas 아, 고마워. 그것을 놓쳤습니다. –

1

document.getElementsByClassName 라이브 인 요소가 자동으로 할 때 자신의 클래스 이름 변경을 제거 할 것이라는 점을 의미한다.

이 시도 : 과거에 사용 된

var hotElements = document.getElementsByClassName("hot"); 
 

 
// While loop to iterate while there are items left 
 
while(hotElements.length > 0) { 
 
    hotElements[0].className = "pink"; 
 
} 
.hot { 
 
    background-color: red; 
 
    color: black; 
 
    font-size: 20px; 
 
    weight: 700; 
 
} 
 
.cool { 
 
    background-color: blue; 
 
    font-size: 25px; 
 
} 
 
.pink { 
 
    background-color: pink; 
 
    font-size: 35px;
<h1 id="header"> List King </h1> 
 
<h2>Buy groceries</h2> 
 
<ul> 
 
    <li id="one" class="hot"> Fresh </li> 
 
    <li id="two" class="hot"> Fresh 1</li> 
 
    <li id="three" class="hot"> Fresh 2 </li> 
 
    <li id="one" class="cool"> Fresh </li> 
 
    <li id="two" class="cool"> Fresh 1</li> 
 
    <li id="three" class="cool"> Fresh 2 </li> 
 
</ul>