2016-08-05 3 views
1

일부 속성을 제거하고 노드 목록에서 일부 속성을 보존해야합니다. 예를 들어, img 요소의 목록이 있고 srcalt 속성 만 있으면 지정된 목록의 요소 특성을 반복 할 수 있습니까?DOM 메서드를 사용하여 특성을 반복합니다?

<img src="" alt="" height="" width="" class="class1"> 
<img src="" alt="" height="" width="" class="class2"> 
<img src="" alt="" height="" width="" class="class3"> 
<img src="" alt="" height="" width="" class="class4"> 
<img src="" alt="" height="" width="" class="class5"> 
<img src="" alt="" height="" width="" class="class6"> 
<img src="" alt="" height="" width="" class="class7"> 
<img src="" alt="" height="" width="" class="class8"> 
<img src="" alt="" height="" width="" class="class9"> 
<img src="" alt="" height="" width="" class="class10"> 

<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
당신은 각 요소에 대한 속성을 반복 속성의 이름을 확인할 수 있습니다

흰색 - 목록을 전년도와 removeAttribute()

var images = document.querySelectorAll('img'); 

for (var i = images.length; i--;) { 
    for (var j = images[i].attributes.length; j--;) { 

     var attribute = images[i].attributes[j]; 

     if (['src', 'alt'].indexOf(attribute.name) === -1) { 
      images[i].removeAttribute(attribute.name); 
     } 

    } 
} 
+0

사용하여 다른 작업을 제거 두 부분이를 즉 제공된 코드가 – MikeT

+0

에 오신 것을 환영합니다 { \t \t \t \t이 \t \t \t을 계속} 경우! [더 좋은 질문을 하시려면] 다른 세부 정보를 제공하십시오 (http://stackoverflow.com/help/how-to-ask) : 귀하가 시도한 것을 나열하고, 인터넷에서 이것을 조사하고, 확실한 해결책이 제공되지 않는 동안 알려주십시오 일하지 마라. 빠른 Google 검색은 [jquery .removeAttr()] (https://api.jquery.com/removeAttr/) 메소드를 켭니다. – emunsing

답변

3
먼저 존재하는 것을 차단하고 두 번째로 원하는 결과를 차단 하시겠습니까? 아마도 첫 번째 블록은 "주어진 목록"일 것입니다. 요소 ID를 사용하는 것이 유리할 수 있습니다 (예 : DIV에있는 경우). 그러면 DIV 요소를 가져 와서 하위 노드를 반복 할 수 있습니다. 예 : `c = document.getElementById (AC_ChildDiv); \t \t (i = 0; i
관련 문제