투케이2K

114. (javascript/자바스크립트) childNodes 자식 리스트 확인 및 자식 속성 nodeName 확인, style 스타일 변경 실시 본문

JavaScript

114. (javascript/자바스크립트) childNodes 자식 리스트 확인 및 자식 속성 nodeName 확인, style 스타일 변경 실시

투케이2K 2021. 8. 12. 10:50
반응형

[개발 환경 설정]

개발 툴 : Edit++

개발 언어 : javascript


[소스코드]

    <!-- 내부 JS 스타일 지정 -->
    <script>

    	/*
    	[JS 요약 설명]
    	1. window onload : 웹 브라우저 로딩 완료 상태를 나타냅니다
    	2. childNodes : 특정 태그에 포함된 자식 노드 리스트를 가져옵니다
    	3. childList[i].nodeName.toLowerCase() : 특정 자식 노드 태그 속성 값을 영문 소문자로 반환합니다
    	4. childList[i].style.backgroundColor : 특정 자식 노드 배경 색상을 지정합니다 	
    	*/


    	/* [html 최초 로드 및 이벤트 상시 대기 실시] */
    	window.onload = function() {
    		console.log("");
    		console.log("[window onload] : [start]");
    		console.log(""); 	

    		// 일반 이벤트 수행 함수를 호출
    		runFunction();
    	};

    	

    	/* [이벤트 수행 함수] */
    	function runFunction(){
    		console.log("");
    		console.log("[runFunction] : [start]");
    		console.log("");

    		// 특정 객체에 포함된 자식 노드 리스트 지정
    		var childList = document.getElementById("multi_container").childNodes;


    		// for 반복문을 수행하면서 자식 노드 특정 태그 개수 확인 실시
    		var divCount = 0;
    		for (var i=0; i<childList.length; i++){
    			if(childList[i].nodeName.toLowerCase() == "div"){ // 노드 속성이 특정 태그인 경우
    				// 카운트 증가 실시
    				divCount ++;

    				// 분기 처리 및 추가 로직 처리
    				if(divCount%2==0){ // 짝수로 나눠떨어지는 경우
    					childList[i].style.backgroundColor = "#eeeeee"; // 자식 색상 변경 (옅은 회색)
    				}
    				else { // 홀수인 경우
    					childList[i].style.backgroundColor = "#999999"; // 자식 색상 변경 (진한 회색)
    				}
    			}
    		}
    		console.log("");
    		console.log("[runFunction] : [divCount] : " + divCount);
    		console.log("");    		  		
    	};

    </script>

[결과 출력]


[요약 설명]

/*

[JS 요약 설명]

1. window onload : 웹 브라우저 로딩 완료 상태를 나타냅니다

2. childNodes : 특정 태그에 포함된 자식 노드 리스트를 가져옵니다

3. childList[i].nodeName.toLowerCase() : 특정 자식 노드 태그 속성 값을 영문 소문자로 반환합니다

4. childList[i].style.backgroundColor : 특정 자식 노드 배경 색상을 지정합니다

*/


 

반응형
Comments