2017-02-06 2 views
0

<select> 인 양식에서 일부 요소를 가져와야했습니다. 요소에 new_cat_inputs 클래스를 추가하고 document.querySelectorAll()까지 가져올 것이라고 생각했습니다.
나는 많은 것들을 시도했지만이 일한 적이, 내가 마지막으로 사용 :JS - 클래스 이름이있는 document.querySelectorAll 이해

document.getElementsByClassName("new_cat_inputs") 

그것은 해결 된 내 문제를 의미하지만 이해하고 싶다.

// first attempt, as I'd have used document.querySelector() which works this way 
document.querySelectorAll(".new_cat_inputs"); 

// Logs an error which says it can't read the property "querySelectorAll" of null (body) 
document.body.querySelectorAll(".new_cat_inputs"); 

// doesn't get the elements neither as the 1st attempt. Neither with document.body 
document.querySelectorAll("label.new_cat_inputs, input.new_cat_inputs, select.new_cat_inputs"); 

내가 종종하는 데 도움이 MDN documentation하지만이 시간을 읽어 여기에
은 전에 시도 것입니다.

전체 문서 기능 document.querySelectorAll()에 의해 자신의 클래스 여러 DOM 요소를 선택 하는 올바른 방법은 무엇입니까? document.body 이후

+1

이는 document.body는'null', 당신의 DOM이로드되지 않았습니다 어쩌면,이 이벤트 리스너 내부에 코드를 삽입하려고 않았다 the following link

건배, 참조 : '창을 .addEventListener ('DOMContentLoaded', function() { // 코드 }) ' ? –

+0

@boehm_s 당신 말이 맞아요. 'window.onload'가 충분하지 않았습니다. – AymDev

+0

하지만 여전히 ... document.getElementsByClassName()은 왜 작동하고'document.querySelectorAll()'이 아닌가요? @ boehm_s – AymDev

답변

1

는이 DOM이로드되지 않음을 의미합니다, 귀하의 예제에서 null을 것 같다. 이 경우 다른 장소 또는 그것을 사용하기 때문에이 행해져 Yout getElementsByClassName 근무 (내가 잘 모르겠어요)

window.addEventListener('DOMContentLoaded', function() { 
    // your code 
}) 

내 생각 : 다음 이벤트 리스너를 사용하면 DOM이로드 될 때까지 기다린 다음 코드를 실행할 수 있습니다 DOM이로드되었습니다. 이 메서드는 라이브HTMLCollection을 반환하므로 DOM을로드하면 업데이트됩니다.

당신의 예에서

+0

두 함수를 같은 장소에서 사용했지만 라이브 'HTMLCollection'에 대한 설명이 더 합리적입니다. 고마워, 오늘 배웠다! – AymDev