리팩토링이란?
외부동작을 바꾸지 않으면서 내부구조의 중복과 동작하지 않는 코드를 지우고 효율성을 높여 성을 높이고 오류를 줄여서 개선하는 작업이라고 한다.

전 과정 부터 시작 하겠다.
<input id="night_day" type="button" value="night" onclick="
if(document.querySelector('#night_day').value === 'night') {
document.querySelector('body').style.backgroundColor='black';
document.querySelector('body').style.color='white';
document.querySelector('#night_day').value='day';
} else {
document.querySelector('body').style.backgroundColor='white';
document.querySelector('body').style.color='black';
document.querySelector('#night_day').value='night';
}
">
코드중 document.querySelector('body').style.backgroundColor=' ' 이 눈에 띈다 길고 4번이나 반복되어있는데 거추장 스러우니 정리해보자!.
onclick동작 다음 var target = document.querySelector('body'); 을 입력해 이제 target은 document.querySelector('body') 이기 때문에 이제 이렇게 수정하면 된다.
<input id="night_day" type="button" value="night" onclick="
var target = document.querySelector('body');
if(document.querySelector('#night_day').value === 'night') {
target.style.backgroundColor='black';
target.style.color='white';
document.querySelector('#night_day').value='day';
} else {
target.style.backgroundColor='white';
target.style.color='black';
document.querySelector('#night_day').value='night';
}
">
그리고 아래의 value 부분도 해주자 document.querySelector('#night_day') 이 코드는 자기 자신을 가리키도 있다. 이 부분을 this 로 수정하면
<input type="button" value="night" onclick="
var target = document.querySelector('body');
if(this.value==='night') {
target.style.backgroundColor='black';
target.style.color='white';
this.value='day';
} else {
target.style.backgroundColor='white';
target.style.color='black';
this.value='night';
}
">
이렇게 하고 인덱스 태그는 지금 부터 this 로 하면 되기 때문에 id=night_day 는 지워주면 되겠다.
잘 작동하는 것을 확인 할 수 있다. 이렇게 작업한다면 똑같은 태그가 몇 개가 추가되도 다로 수정없이 사용이 가능하다.
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length) {
alist[i].style.color = 'powderblue';
i = i + 1;
}
alist 에 document.querySelectorAll('a'), i 초기값을 0 으로 두고 alist 길이 작은 만큼 반복, alist 의 색을 powderblue 색으로 변경하고 i 에 1을 더한다.
document.querySelectorAll('a') 를 사용하는 이유는 document.querySelector('a') 는 a 태그의 첫번째 만 가져오기 때문에 a 태그를 전부 가져오기 위해서 사용하였다. <input type="button" value="night" onclick="
var target = document.querySelector('body');
if(this.value==='night') {
target.style.backgroundColor='black';
target.style.color='white';
this.value='day';
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length) {
alist[i].style.color = 'powderblue';
i = i + 1;
}
} else {
target.style.backgroundColor='white';
target.style.color='black';
this.value='night';
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length) {
alist[i].style.color = 'blue';
i = i + 1;
}
}
">

정상적으로 night 일때는 powderblue 색상, day 에는 blue 색상으로 글자가 변경 된다.