JavaScript

[2일차] JavaScript의 데이터 입출력, 접근법

Dodledd 2024. 3. 15. 16:59

자바스크립트에서의 데이터 입출력

window : 자바스크립트의 내장 객체로 브라우저창이 열릴 때 마다 하나씩 만들어지는 객체 
                브라우저 창 안에 존재하는 모든요소들의 최상위 객체(생략가능)
                 window.alert();이지만 alert();만 써도 된다. 
document : 웹 문서마다 하나씩 만들어지는 객체(html 문서에 대한 정보들을 가지고 있음)

 

1) [window.]alert("출력하고자하는 문구"); 
2) [window.]console.log("콘솔창에 출력하고자하는 문구")
3) document.write("화면상에 출력하고자하는 문구")
4) 선택한요소.innerHTML | 선택한요소.innerText = "요소에 출력할 문구";\

[window]는 생략이 가능하다.

 

 

alert, console

    <script>
      alert("안녕하세요");
      console.log("안녕하세요");
    </script>

alert : 팝업창에 띄워진다.

console : 개발자도구의 콘솔창에 출력된다.

 

alert
console.log

 

document.write

document.write("화면상에 출력하고자하는 문구");

 

<button onclick="documentWrite()">화면에 출력</button>

    <script>
      function documentWrite() {
       
        let str =
          "<table border='1'>" +
          "<tr>" +
          "<td>1</td>" +
          "<td>2</td>" +
          "</tr>" +
          "</table>";

        documentWrite(str);
      }
    </script>

 출력할 문구에 html 태그에 있을 경우 해석해서 시각적인 요소로 보여진다.

 

innerHTML   |    innerText

선택한요소.innerHTML | 선택한요소.innerText = "요소에 출력할 문구";
    <div class="area" id="area1">
    <button onclick="tagValue()">확인</button>
	<script>
      function tagValue() {
        //위의 div 요소 가져와서 안에 있는 값을 확인 / 변경

        //div 요소객체를 가져와서 변수에 담아두기
        let divE1 = document.getElementById("area1");
        console.log(divE1);

        //선택된 요소의 속성에 접근 가능(.을 통해서 접근)
        console.log(divE1.id);
        //해당 요소의 아이디 속성
        id: console.log(divE1.className); //해당 요소의 클래스 속성

        console.log(divE1.innerHTML); //innerHTML : 요소의 content영역 안의 html까지 전부 포함해서 가져온다
        console.log(divE1.innerText); //innerText : 요소의  content영역 안의 텍스쳐만 포함해서 가져온다

        divE1.innerText = "<b>innerText로 속성값 변경함</b>";

        divE1.style.backgroundColor = "yellow";
      }
    </script>

 

  1. 확인 button이 클릭되면 tagValue()함수를 실행
  2. script 영역 안에 function tagValue()를 정의
  3. 주석을 읽으며 차근차근 이해

버튼 클릭 전
버튼 클릭 후

 


데이터를 입력받는 구문(변수에 기록)

1) 변수 = [window.]confirm("질문내용");
2) 변수 = [window.]prompt("질문내용");
3) 변수 = [window.]선택한요소.속성(id, className, innerText ...)
4) 선택한 input요소.value

[window]는 생략가능

 

 

 confirm

[window.]confirm("질문내용");


confirm 호출시 "질문내용"과 확인/취소 버튼이 존재하는 알림창 발생
확인버튼 클릭시 true, 취소버튼 클릭시 false를 반환
<div id="area2"></div>
    <button onclick="testConfirm();">클릭</button>


    <script>
      function testConfirm() {
        let result = confirm("눌리면 확인, 아니면 취소를 누르세요");
        // console.log(result);

        let divE2 = document.getElementById("area2");
        if(result){
            divE2.innerHTML = "<h3> 정신차리세요 </h3>";
        }else{
            divE2.innerHTML = "<h3> 굿</h3>";
        }
      }
    </script>

 

  1. 마찬가지로 버튼이 클릭되면 testConfirm()을 실행
  2. script영역에서 testConfirm()을 정의
  3. 주석 읽어보기

확인, 취소 누를 시
onclick화면

 

 

prompt

[window.]prompt("질문내용");

prompt 호출시 "질문내용"과 입력할 수 있는 "텍스트 상자"와
"확인/취소" 버튼이 보여지는 알림창 발생
확인버튼 클릭시 텍스트상자에 입력되어있는 값이 문자열로 반환
취소버튼 클릭시 null을 반환(값을 입력했더라도 취소를 클릭시 null반환)
<button onclick="testPrompt();">클릭</button>
     <div id="area3"></div>
    <script>
        function testPrompt(){
            let name = prompt("당신의 이름은 무엇입니까?");
            let age = prompt("당신의 나이는 몇살입니까?");

            divE3 = document.getElementById("area3");
            divE3.innerHTML = "당신은" + age + "살 <b>" + name + "</b>이시군요";
        }
    </script>

 

클릭버튼 누르기 전
누르고 입력창에 값을 입력한 후

input

선택한 input요소.value
아이디 : <input type="text" id="userId"> <br>
    비밀번호 : <input type="password" id="userPwd"> <br>

    <button onclick="testInput()">클릭</button>
    <br>
    <input type="text" id="area4">

    <script>
        function testInput(){
            let input1 = document.getElementById("userId"); //id입력받는 거 만들고
            let input2 = document.getElementById("userPwd"); //password입력받는거 만든ㄹ고

            console.log(input1.value); //id확인용
            console.log(input2.value); //id확인용

            document.getElementById("area4").value = input1.value + ", " + input2.value;

            input1.value = "";
            input2.value = "";
        }
    </script>

입력 후 html과 콘솔창


요소에 접근하기

HTML 요소에 접근하기(해당요소 객체 가져오기)

 

방법 1. 아이디를 이용해서 요소 가져오기

아이디는 유일하기 때문에 하나만 가져온다 -> 일반값

<div id="area1" class="area"></div>
    <button onclick="accessId()">아이디로 접근</button>

    <script>
        function accessId(){        //아이디로 요소 가져올 때
        //document.getElementById("아이디명") => 선택된 요소객체 반환

        document.getElementById("area1");

        //선택한 요소의 속성값을 가져온다거나 변경 가능
        //속성에 접근하고자 할 때 -> 선택된요소.접근하고자하는 속성

        // area1.innerHTML = "아이디로 접근 성공! <br>"
        area1.innerHTML += "아이디로 접근 성공! <br>"

        area1.style.background= "yellow";
        area1.style.color= "red";
        area1.style.width = "200px";
        area1.style.height = "200px";
        }


    </script>

 

 

응용해서 빨강, 노랑으로 바꾸기

 <div id="area2" class="area"></div>

    <button onclick="changeColor();">클릭 시 색상 변경</button>

    <script>
        function changeColor(){
            //버튼이 클릭될 때 마다 area2의 배경색상을 노랑 -> 빨강 반복해서 바꿔주세요
        
            let area2 = document.getElementById("area2");

            if(area2.style.background!= 'yellow'){
                area2.style.background = 'yellow';
            }else{
                area2.style.background = 'red';
            }
        }
    </script>

 

방법 2. 태그명을 이용해서 요소 가져오기

 

문법은 거의 자바랑 비슷해서 배열의 길이를 구하는 length도 잘 된다.

또 태그명은 여러개의 중복이기 때문에 배열로 가져온다. [1, 2, 3, 4 ...]

<ul>
        <li>안녕하세요1</li>
        <li>안녕하세요2</li>
        <li>안녕하세요3</li>
        <li>안녕하세요4</li>
        <li>안녕하세요5</li>
    </ul>

    <button onclick="accessTagName();">태그명으로 접근</button>

    <script>
        function accessTagName(){
            //태그명으로 요소 가져올 때
            // document.getElementById("태그명") =>선택된 요소객체들이 배열로 반환

            let list = document.getElementsByTagName('li'); //[li, li, li ...]
            console.log(list);
            console.log("배열의 길이" + list.length);
            
            for(let i = 0; i<list.length ; i++){
                console.log(list[i].innerHTML);
            }

            for(let i = 0; i<list.length ; i++){
                list[i].innerHTML = (i+1) +" 번째 li요소입니다.";
                list[i].style.color = "red";
            }
        }
    </script>

 

 

방법 3. name 속성값을 이용해서 요소 가져오기

 

체크박스는 onchange라는 트리거를 사용 가능하다

onchange = 값이 변했을 때를 감지해서 ture, false가 된다.

    <form action="">
        <fieldset>
            <legend>취미</legend>
            <input type="checkbox" name="hobby" value="전체선택" id="all" onchange="allCheck()">
            <label for="all">전체선택</label>
            <input type="checkbox" name="hobby" value="게임" id="game" onchange="checkBoxTrigger()">
            <label for="game">게임</label>
            <input type="checkbox" name="hobby" value="영화" id="movie" onchange="checkBoxTrigger()">
            <label for="movie">영화</label>
            <input type="checkbox" name="hobby" value="운동" id="sport" onchange="checkBoxTrigger()">
            <label for="sport">운동</label>
        </fieldset>
    </form>

    <div id="area3" class="area"></div>

    <button onclick="accessName()">name으로 접근</button>
    <script>
        function allCheck(){
            let allCheckBox = document.getElementById("all");

            let hobbyList = document.getElementsByName("hobby");

                for(let checkbox of hobbyList){
                    checkbox.checked = allCheckBox.checked;
                }
            }

 

추가 메소드로 전체선택을 누를면 모두 선택하게 되는 함수를 만들자

 

<script>
function checkBoxTrigger(){            
            //전체체크박스이외에 체크박스들의 상태에 따라서 전체체크박스를 true, false로 변경하고싶다.
            //ture -> 나머지 모든체크박스가 ture일 때 true
            //false -> 하나라도 false라면 false
            let allCheck = true;

            let hobbyList = document.getElementsByName("hobby");
            for(let checkbox of hobbyList){
                if(checkbox.value == "전체선택"){
                    continue;
                }

                //checkBox중 한개라도 checked가 false라면 전체선택 체크박스의 checked는 false여야 한다.
                if(!checkbox.checked){
                    allCheck = false;
                }
            }

            let allCheckBox = document.getElementById("all");
            allCheckBox.checked = allCheck;//true, false
  
        }
</script>

전체선택을 누르면 모든 값을 true만드는데 자기 자신은 제외해야 하기때문에 checkbox.value == 전체선택인 경우는 제외하여 continue로 진행시킨다.

 

방법 4. class로 접근

<div class="test"></div>
    <p class="test"></p>
    <ul class="test">
        <li></li>
        <li></li>
    </ul>
    <pre class="test test1 test2"></pre>
    <button onclick="accessClass()">class로 접근</button>


    <script>
        function accessClass(){
            //class속성으로 요소 가져올 때
            //document.getElementsByName("클래스 속성 값") -> 선택된 요소들의 배열 반환

            let arr = document.getElementsByName('test');
            console.log(arr);

            for(let unit of arr){
                unit.innerHTML = "test를 가지고 있는 요소";
                
            }
            
        }
    </script>

 

방법 5. 선택자 활용

 

가장 많이 사용하는 방법이다. 내가 원하는 요소를 자유자재로 가져오기 편하기 때문에 인기가 많다고 한다.

 <div id="tmp1">테스트입니다</div>
    <div class="tmp2">
        <h2>안녕하세요.</h2>
        <h2>빵빵이 입니다.</h2>
    </div>
    <span>오잉? span</span>
    <h2>옥지얌</h2>
    <br>

    <button onclick="accessSelector()">클릭</button>

    <script>
        function accessSelector(){
            //선택자를 이용해서 요소를 가지고오고자 할 때
            // document.querySelector("선택자"); -> 선택된 요소 한개만 반환
            // document.querySelectorAll("선택자"); -> 선택된 요소 객체들을 배열에 담아서 반환
        
            const divT1 = document.querySelector("#tmp1"); // div
            const h2E1 = document.querySelectorAll(".tmp2 > h2"); //[h2, h2]
            const spanE1 = document.querySelector(".tmp2 + span");
            console.log(divT1);

            for(let el of h2E1){
                console.log(el);
            }

            console.log(spanE1);

            const h2Tmp = document.querySelector("span + h2");
            h2Tmp.innerHTML = "어이";
        
        }
    </script>

 

옥지얌이 어이로 바뀌게된다.

 

 

 

이렇게 몇개 배워봤다.

다음 포스팅에는 JavaScript에서 사용되는 변수를 정리해보겠다 !