본문 바로가기

WEB FRONT/JavaScript

[JavaScript] 기초 정리

[ JS 개요 ]

▶ 스크립트(Script) 언어 : 

기본 프로그램의 동작을 사용자의 요구에 맞게 수행되도록 해주는 용도의 언어

별도로 소스코드를 컴파일하지 않고, 인터프리터(interpreter)를 이용하여 소스코드를 한 줄씩 읽어 바로 실행함

 

-> 컴파일에 소요되는 시간이 없는 대신, 프로그램 실행시간이 느리다.

    짧은 소스코드 파일로 상호작용 하도록 고안해야함

 

자바스크립트(JavaScript)란 :

웹 브라우저에서 많이 사용하는 인터프리터 방식의 객체 지향 프로그래밍 언어

ECMA Script 표준을 따르는 대표적인 웹 기술이다

 

자바스크립트 작성방법

1) 브라우저 검사-콘솔에 직접 작성 가능 (테스트 용도)

 

2) html 내부에 script 태그를 이용해 작성 (internal)

<button type="button" onclick="btnClick1()">internal 방식</button>

<script>
    function btnClick1(){
        alert("internal 버튼이 클릭되었습니다.");
     }
</script>

 

3) html 외부에 (.js)파일을 이용해 작성 (external)

 * head, body태그 어디든 js연결 태그 작성가능

 <script src="js/01_개요.js"></script>

 <button type="button" onclick="btnClick2()">external 방식</button>

 

01_개요.js

 function btnClick2(){
     alert("external 버튼이 클릭됨 ~");
 }

 

4) 태그에 직접 js코드를 작성하는 inline 방식

 *JavaScript는 "" '' 둘 다 문자열 리터럴 표기방법으로 인식함

 <button type="button" onclick="alert('inline 버튼 클릭됨 ~')">inline 방식</button>

 

-------------------------------------------------------------------------------------------------

[데이터 입출력]

▶ innerText

- 자바스크립트에서 요소에 작성된 내용을 읽어들이거나 변경하는 속성

- 내용을 읽어올 때 태그는 모두 무시 (글만 읽어옴)

- 내용을 변경할 때 태그는 단순 문자열로 인식 (태그해석 X)

 

1) innerText로 읽어오기

HTML <button type="button" onclick="getInnerText()">innerText로 읽어오기</button>
    <p id="test1" class="box">
        테스트1 입니당.
        <br>
        <b>안녕하세요?</b>
    </p>
JS function getInnerText(){
    const test1 = document.getElementById("test1");
    console.log(test1.innerText);
}

[콘솔]

테스트1 입니당.
안녕하세요?

 

innerText로 읽어오는 경우

텍스트만 출력됨, 작성된 태그는 해석되지 않고 무시된다

 

2) innerText로 변경하기

HTML <button type="button" onclick="setInnerText()">innerText로 변경하기</button>
    <p id="test1" class="box">
        테스트1 입니당.
        <br>
        <b>안녕하세요?</b>
    </p>
JS function setInnerText(){
    const test1 = document.getElementById("test1");
    test1.innerText = "innerText로 변경된 <br> 내용입니다.";   
}

[콘솔]

innerText로 변경된 <br> 내용입니다.

 

innerText로 변경하는 경우,

입력 태그를 단순 문자열로 인식하여 함께 출력된다

 

▶ innerHTML

- 자바스크립트에서 요소 전체를 읽어들이거나 변경하는 속성

- 내용을 읽어올 때 태그 + 속성 모두 포함 

- 내용을 변경할 때 태그는 HTML요소로 인식 (태그 해석O)

 

1) innerHTML로 읽어오기

HTML <button type="button" onclick="getInnerHTML1()">innerHTML로 읽어오기</button>
    <p id="test2" class="box">
        테스트2입니다.
        <br>
        <b>안녕하세요?</b>
    </p>  
JS function getInnerHTML1(){
    const test2= document.getElementById("test2");
    console.log(test2.innerHTML);
}

[콘솔]

        테스트2입니다.
        <br>
        <b>안녕하세요?</b>

 

innerHTML로 읽어오는 경우

test2 요소 내부의 내용(태그, 속성, 내용)을 모두 읽어옴)

 

 

2) innerHTML로 변경하기

HTML <button type="button" onclick="setInnerHTML1()">innerHTML로 변경하기</button>
    <p id="test2" class="box">
        테스트2입니다.
        <br>
        <b>안녕하세요?</b>
    </p>  
JS function setInnerHTML1(){
    const test2 = document.getElementById("test2");
    test2.innerHTML = " <b>innerHTML로 변경된 내용입니다.</b> <br> 반가워용";
}

[콘솔]

 <b>innerHTML로 변경된 내용입니다.</b> <br> 반가워용

 

innerHTML로 변경하는 경우,

test2 요소 내부의 내용(태그, 속성, 내용)을 html 요소로 해석한다.

 

▶ window.alert("내용") :

브라우저에 알림 대화상자를 띄우는 함수

 

function fnAlert(){
    window.alert("alert 버튼 클릭됨");
    // window 는 브라우저 자체를 나타내는 객체 
    // js코드는 브라우저(window) 내부에서 실행되는 코드이다보니 window를 생략가능
}

 

▶ window.confirm("내용") :

질문에대한 예 혹은 아니오 결과를 얻고자 할 때 사용하는 함수

선택 결과에 따라 true 혹은 false 반환

 

function fnConfirm(){
    if(window.confirm("버튼 배경색을 pink로 변경하시겠습니까 ??")){
        document.getElementById("confirmBtn").style.backgroundColor = "pink";
    }else{
        document.getElementById("confirmBtn").style.backgroundColor = "#efefef";
    }
}

 

▶ window.prompt("내용") :

텍스트를 작성할 수 있는 대화상자

확인 클릭시 입력값 반환, 취소 클릭시 null 반환

 

function fnPrompt(){
    const input = prompt("이름을 입력해주세요.");
    const promptResult = document.getElementById("promptResult");


    if(input!=null){
        promptResult.innerText = input+"님 환영합니다.";
    }else{
        promptResult.innerText = "이름을 입력해주세요,,,";
    }
}

 

-------------------------------------------------------------------------------------------------

[요소 접근방법]

DOM (Document Object Model)

웹 문서(html)의 모든 요소를 객체 형식으로 표현,

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

 

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

const div1 = document.getElementById("div1");



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

 

const arr = document.getElementsByClassName("div2");

arr[0].style.backgroundColor = "pink";
arr[0].innerText = "pink";

arr[1].style.backgroundColor = "tomato";
arr[1].innerText = "tomato";

arr[2].style.backgroundColor = "blue";
arr[2].innerText = "blue";


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

 

보통 값을 얻어와 콘솔에 출력할 때에는

innerText, innerHTML를 사용하는데,

이 두가지는 요소의 내용 (시작태그~종료태그 사이에 작성된 내용)을 얻어오거나 변경할때만 사용 가능하다.

★ input태그는 [value]를 이용해 값을 얻어오거나, 변경할 수 있음을 인지해야함 ★

const input = document.getElementById("input-test");

console.log(input.value);

input.value = ""; // 빈 문자열 == value 지우기

input.focus(); // 입력버튼 클릭 후에도 입력창에 focus 잡혀있음 (커서)

 

이를 이해하고 name속성으로 접근하기를 알아보자.

const hobbyList = document.getElementsByName("hobby");
// checkbox에는 동일한 name속성이 여러개 들어올 수 있어 배열 형태로 반환됨

let str = "";
let count = 0;

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

    //radio, checkbox 전용 속성 : .checked 체크시 true, 아니면 false 반환
    
    if(hobbyList[i].checked){
        // str 변수에 value 누적
        str += hobbyList[i].value + " ";
        count ++;
    }
}

// #name-div 에 출력
document.getElementById("name-div").innerText = str;
document.getElementById("name-div").innerHTML += "<br><br> 선택된 개수: "+ count;

 

4. tag로 접근하기 : document.getElementsByTagName("tag명");

 

const arr = document.getElementsByTagName("li");

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

    const num = arr[i].innerText;
    // 요소에 작성된 숫자 얻어오기

    arr[i].style.backgroundColor = "rgb(50, 50, "+(50*num)+")";

}


5. css 선택자로 접근하기 (나머지 네 개의 방법보다 속도가 약간 느림 ~ )
 1) document.querySelector("css선택자");
 -> 선택된 요소가 여러개일 경우 첫 번째 요소만 접근함

// 한개만 있는 요소 선택
document.querySelector("#css-div").style.border = "3px solid red";

//여러개 있는 요소 선택 -> 첫번째 요소만 선택됨을 확인할 수 있음
document.querySelector("#css-div>div").style.fontSize = "40px";


 2) document.querySelectorAll("css선택자");
 -> 선택된 요소 모두 접근

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

for(let i=0; i <arr.length; i++){
    arr[i].style.backgroundColor = "gold";
}

 

'WEB FRONT > JavaScript' 카테고리의 다른 글

[JavaScript] 이벤트  (0) 2022.05.17