YJ의 새벽

Java Script ( DOM , 요소접근방법 ) 본문

WebFront_/Java Script

Java Script ( DOM , 요소접근방법 )

YJDawn 2023. 2. 23. 18:15

 

 

 

  • DOM (Document Object Model)

-- 웹 문서(HTML)의 모든 요소를 객체 형식으로 표현하는 방법

   --> 문서 내 특정 요소에 접근하는 방법을 제공

 

 

 

  • DOM 을 이용한 요소 접근 방법

1. id 속성 값으로 접근하기   (  document . getElementById ("id속성값") ;

2. class 속성값으로 접근하기  (   document . getElementsByClassName ( "class속성값" );

                : 배열  arr[0], arr[1] ...  로 접근한다 .

3. name 속성값으로 접근하기  (  document . getElementsByName ("name속성값");

                : 배열  arr[0], arr[1] ...  로 접근한다 .

4. tag name 으로 접근하기.   (  document . getElementsByTagName ("태그명");

                : 배열  arr[0], arr[1] ...  로 접근한다 .

5. css 선택자를 이용 접근하기

   1)   document . querySelector ( "#test" );

            - 단일 요소를 선택하는방법.

            - 만약 선택된 요소가 여러개라면 첫번째 요소만 선택.

   2)   document . querySelectorAll (" css선택자 ") ;

            - 선택된 모든 요소를 얻어와 배열 형태 반환

                   (각각의 index에 선택된 요소가 하나씩있음.)

 

 

 

 

 

 

 

 

  EX  ))))    id 로 접근하기 .

 

    <button onclick="fnTest1()">클릭할 때 마다 배경색 변경</button>
    <div id="div1" class="area"></div>
function fnTest1(){

    // id가 "div1" 인 요소를 얻어와 상수 div1에 저장
    const div1 = document.getElementById("div1");
    // 접근한 요소의 배경색을 얻어와 변수(bgColor)에 저장
    const bgColor=div1.style.backgroundColor;

    if(bgColor == 'red' ){
        div1.style.backgroundColor="yellow";
    }else if(bgColor=='green'){
        div1.style.backgroundColor="red";
    }else{
        div1.style.backgroundColor="green";
    }
}
Document

 

 

 

 

 

 

 

 

 

  EX  ))))   class 로 접근하기 .

    <div class="area div2"></div>
    <div class="area div2"></div>
    <div class="area div2"></div>
    <button onclick="fnTest2()">배경색 변경하기</button>
function fnTest2(){
    const arr = document.getElementsByClassName("div2");

    arr[0].style.backgroundColor="green";
    arr[1].style.backgroundColor="yellow";
    arr[2].style.backgroundColor="red";

    for(let i = 0; i < arr.length; i++){
        arr[i].innerText= i + '번째 요소입니다';
    }
}
Document

 

 

 

 

 

 

 

 

 

 

     EX )))) 태그명으로 접근하기

 

    <ul>
        <li>20</li>
        <li>80</li>
        <li>140</li>
        <li>200</li>
        <li>255</li>
    </ul>
    <button onclick="fnTest3()">배경색 변경하기</button>
function fnTest3(){
    
    //문저내 존재하는 모든 li 요소들을 배열형식으로 반환
    const arr = document.getElementsByTagName("li");

    for(let i=0; i<arr.length; i++){
       const num = arr[i].innerText;

       arr[i].style.backgroundColor="rgb(100,"+num+" ,130)";
    }
}
Document
  • 20
  • 80
  • 140
  • 200
  • 255

 

 

 

 

 

 

 

 

 

 

     EX ))))  input태그의 값 (value) 얻어오기 

    <input type="text" id="inputTest">
    <button onclick="fnTest4()">입력</button>
function fnTest4(){
                                               
    const input = document.getElementById("inputTest");  //input 요소 접근하기

    //input 관련태그 작성된 값 나타내는속성 == value
 
    alert(input.value);                //input 값을얻어와 alert으로 출력

    input.value=" ";
}
Document

input태그의 값(value) 얻어오기/변경하기

 

 

 

 

 

 

 

       EX  )))   name 속성으로 접근하기 

 

<table>
        <tr>
            <td>
                <label>
                    <input type="checkbox" name="hobby" value="게임">게임
                </label>
            </td>
            <td>
                <label>
                    <input type="checkbox" name="hobby" value="음악감상">음악감상
                </label>
            </td>
            <td>
                <label>
                    <input type="checkbox" name="hobby" value="영화감상">영화감상
                </label>
            </td>
        </tr>
        <tr>
            <td>
                <label>
                    <input type="checkbox" name="hobby" value="운동">운동
                </label>
            </td>
            <td>
                <label>
                    <input type="checkbox" name="hobby" value="독서">독서
                </label>
            </td>
            <td>
                <label>
                    <input type="checkbox" name="hobby" value="코딩">코딩
                </label>
            </td>
        </tr>
    </table>

    <button onclick="fnTest5()">선택완료</button>

    <div class="area" id="result5"></div>
function fnTest5(){
             //name 속성값이 "hobby" 요소를 모두얻어와
             //배열형식으로 반환
    const hobbyArr =document.getElementsByName("hobby");
    
    let str = "";      //체크된 체크박스값을 누적할변수
    let count = 0;         //체크갯수 카운트

    for(let i=0; i<hobbyArr.length; i++){


        if(hobbyArr[i].checked){  //체크된 경우
            str += hobbyArr[i].value +" ";
            count ++; 
        }
    }
    const result=document.getElementById("result5");
    
    if( str !=""){  //체크된것이 하나라도 있을때
        result5.innerText = str;
        result5.innerHTML +="<br><br>선택된 개수 : "+count;
    }else{
        result5.innerText="선택된 취미 없습니다";
    }
}
Document

 

 

 

 

 

 

 

 

 

 

 

       EX ))))   CSS 선택자로 접근하기 

 

    <div id="cssTest">
        <div class="area">test1</div>
        <div class="area">test2</div>
    </div>
    <button onclick="fnTest6()">확인하기</button>
function fnTest6(){
    // id 속성값이 "cssTest"인 요소를 1개 선택
    // (여러 요소가있는경우 첫번째요소만 선택)
    document.querySelector("#cssTest").style.border ="3px solid green";

    document.querySelector("#cssTest > div").style.backgroundColor="gold";

    const arr =document.querySelectorAll("#cssTest > div");

    for( let i=0; i<arr.length; i++){
        arr[i].style.fontSize ='30px';
    }
}
Document
test1
test2

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'WebFront_ > Java Script' 카테고리의 다른 글

Java Script ( 이벤트 )  (0) 2023.02.24
Java Script ( 간이계산기 )  (0) 2023.02.24
Java Script ( 변수 )  (0) 2023.02.24
Java Script ( 채팅창구현 )  (0) 2023.02.23
Java Script 방식  (0) 2023.02.23
Comments