자바스크립트

 

 

 

 

 

 

 

강의 목록  :      https://www.youtube.com/playlist?list=PLZKTXPmaJk8JVQv3XSNF8yJMdsxbFrO3S

 

 

 

 

1 .노드에 접근하기

 

 

HTML의 아이디, 클래스, 태그, 네임을 그대로 작성해준다.

  • document.getElementByID()
  • 태그,클래스,name은 배열로 반환한다.
    • document.getElementsByClassName()
    • document.getElementsByTagName()
    • document.getElementsByName()

CSS 선택자 작성과 동일하게 사용!

  • document.querySelector()
  • document.querySelectorAll() : 해당되는 요소의 첫번째 값만 반환한다.

HTML 요소의 생성

  • document.createElement() : 지정된 HTML 요소를 생성 > 오브젝트를 넘기는것
  • document.write() : HTML 출력 스트림을 통해 텍스트 출력 > 단순 출력

HTML 이벤트 핸들러 추가

  • 요소.onclick = function() {}
  • function (”click”, function객체)

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>1.노드에 접근하기</title>
</head>
<body>
    <ul>
        <li>aaaa</li>
        <li>bbbb</li>
        <li>cccc</li>
        <li>dddd</li>
        <li>eeee</li>
    </ul>
<script>
const pList =document.querySelectorAll("li:nth-of-type(2n)")    
for(p of pList){
    p.style.backgroundColor='#000';
    p.style.color="#fff";
}
</script>    
</body>
</html>

 

 

 

 

 

 

2.부모, 자식, 형제 노드

HTMLCollection  => 실시간  변경감지  하나 NodeList  아니다.

 

1) childNodes: 자식 노드에 접근  ==> NodeList  이나 childNodes 는 예외적으로 실시간 변경 감지

현재 요소의 자식 노드가 포함된 NodeList를 반환합니다. 이때 반환되는 NodeList에는 요소 노드뿐만 아니라 주석 노드와 같은 비 요소 노드를 포함합니다. 

 

document.querySelector("div").childNodes

ul.firstChild;

ul.lastChild;

 

 

 

 

2) children: 자식 요소에 접근  HTMLCollection  => 실시간  변경감지

현재 요소의 자식 요소가 포함된 HTMLCollection을 반환합니다. 비 요소 노드는 모두 제외됩니다.

 

document.querySelector("div").children

 

ul.firstElementChild

ul.lastElementChild

 

 

 

요소 노드 이외의 노드가 필요하지 않은 경우라면 children 프로퍼티를 사용 할것.

 

 

 

 

 

3.노드 생성, 추가, 복제, 삭제

 

 

1. 노드 추가

   노드의 생성 메소드: createElement() 

   노드를 생성하고 기존의 노드에 추가 하는 메소드:  addendChild(), append(), insertBefore()

    - addendChild(), append() => 는 기준 노드의 마지막 자식 요소로 추가.

    - insertBefore() => 는 기준 노드의 앞쪽으로 추가한다.

  •  appendChild() 는 노드객체만을 받을 수 있고, 하나의 노드만을 추가할 수 있다.  
  • return값을 반환한다.
  • append() 는 노드객체와 string(text)를 사용할 수 있고, 여러개의 요소를 추가할 수 있다.  
  • return값을 반환하지 않는다.
  • insertBefore()

        insertBefore(추가노드,기준노드)형식으로 사용한다. 기준노드가 생략되면 appendChild()처럼 제일 마지막에 추가 된다.

 

 

2.  노드 복사

   메소드 cloneNode()

   - cloneNode(true) : true를 넣어주면 자식 노드까지 복사됨

  • cloneNode(true) 

 

3.  노드 삭제

   메소드 remove(), removechild()

   - remove() : 해당 노드를 메모리에서 삭제하고 종료.리턴값 없음

   - removechild() :

           부모-자식 관계를 DOM트리에서 해제, 메모리에 노드 존재, 해제한 노드 참조 리턴.부모 노드에서만 삭제 가능 => 부모요소.removechild();

  • remove()

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3.노드 생성, 추가, 복제, 삭제</title>
</head>
<body>
<h1>Welcome</h1>
<h2>World</h2>
<ul id="color">
    <li id="red">Red</li>
    <li id="blue">Blue</li>
    <li id="green">Green</li>
</ul>
<h3>A</h3>

<script>
    const newLi=document.createElement("li");
    const newText=document.createTextNode("pink");
    newLi.appendChild(newText);
    const ul=document.getElementById("color");
    ul.appendChild(newLi);

    const newLi2=document.createElement("li");
    const newText2=document.createTextNode("black");
    newLi2.appendChild(newText2);
    //(method) Node.insertBefore<HTMLLIElement>(node: HTMLLIElement, child: Node): HTMLLIElement
    ul.insertBefore(newLi2, red);

    ul.appendChild(red);

    const newBlack=newLi2.cloneNode(true);
    ul.appendChild(newBlack);


    //삭제
    ul.removeChild(newBlack);
    ul.removeChild(ul.firstElementChild);
    ul.removeChild(ul.lastElementChild);

</script>    
</body>
</html>

 

 

 

 

 

 

4.CSS style, class 제어

 

 

예1)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>4.CSS style, class 제어</title> 
</head>
<body>
    <div id="box">Box</div>
    <ul id="color">
        <li>Red</li>
        <li>Green</li>
        <li>Blue</li>
    </ul>
<script>
    const box=document.getElementById("box");

    box.style.backgroundColor='red';
    box.style.color="#fff";
    box.style.width="100px";
    box.style.height="100px";
    box.style["margin-left"]="30px";

    box.style.border="10px solid #000";
</script>    
</body>
</html>

 

 

 

예2)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>4.CSS style, class 제어</title>
<style>
    *{
        font-size: 1.5rem;
        font-weight: 600;
    }
    .box{
        width: 100px;
        height: 100px;
        border: 4px solid #000;
    }
    .bg-red{
        background-color: #f00;
    }
    .bg-green{
        background-color: #0f0f;
    }
    .bg-blue{
        background-color: #00f;
    }
    .txt-white{
        color:#fff;
    }
    .txt-yellow{
        color: #ff0;
    }
    .txt-pink{
        color: pink;
    }
</style>    
</head>
<body>
    <div id="box" class="box bg-red">Box</div>
    <ul id="myColor">
        <li>Red</li>
        <li>Green</li>
        <li>Blue</li>
    </ul>
<script>
    // box.className="bg-red";
    // box.className="bg-blue";
    //console.log(box.classList);

    //클래스 추가
    box.classList.add("txt-white", "bg-blue" ,"ok1", "ok2");

    //클래스 삭제
    box.classList.remove("ok1");


    //클래스 변경
    box.classList.replace("bg-blue", "bg-green");

    //토글
    setInterval(()=>{
        box.classList.toggle("bg-green");
    }, 1000);

    //const box=document.getElementById("box");
    //const color=document.getElementById("color");
    //아이디값은 변수 선언없이 다이렉트 가능
    myColor.onclick=function(e){
        const target =e.target;
        console.log(target.tagName);
        //if(target.tagName!=="LI") return;
        target.classList.toggle("txt-pink");
    }



</script>    
</body>
</html>

 

 

 

 

5.이벤트 핸들러(Event Handler)

 

예1)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>5.이벤트 핸들러(Event Handler)</title>
</head>
<body>
    <button onclick="alert('click')">클릭1</button>
    <button onclick="sayHello()">클릭2</button>
    <button id="btn">클릭3</button>
    <button id="btn2">클릭4</button>

    <input type='button' id='delete_event' value='이벤트 삭제' />
<script>
    function sayHello(){
        alert("Hello");
    }
    const el=document.getElementById("btn");
    el.onclick=sayHello;

    const el2=document.getElementById("btn2");
    
    //1. 이벤트 추가 - addEventListener
    //el2.addEventListener("click", sayHello);
    el2.addEventListener("click", ()=>{
        alert("Hi");
    });


    document.addEventListener("DOMContentLoaded",()=>{
        document.body.style.backgroundColor="red";
    });


    //2.이벤트 삭제 - removeEventListener(type ,eventListener);
    // - type : 삭제할 이벤트 타입
    // - eventListener : 삭제할 이벤트 리스터 
    //(addEventListener()의 2번째 파라미터로 전달된 함수)

</script>    
</body>
</html>

 

 

예2)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>5.이벤트 핸들러(Event Handler)</title>
</head>
<body>
    <button id="btn">클릭</button>
    <input id="txt"  type="text" />
    <br>
    <input id="txt2" type="text" />
<script>
    function sayHello(){
        alert("Hello");
    }
    const el =document.getElementById("btn");
    el.addEventListener("dblclick", sayHello);

    const input=document.getElementById("txt");
    input.addEventListener("keyup", (event)=>{
        console.log(event.key);
        console.log(event.target.value);
    });


    const input2=document.getElementById("txt2");
    input2.addEventListener("focus", ()=>{
        input2.style.backgroundColor='rgba(255,0,0,0.2)';
    });
    input2.addEventListener("blur", ()=>{
        input2.style.backgroundColor=null;
    });

</script>
</body>
</html>

 

 

 

예3)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>5.이벤트 핸들러(Event Handler)</title>
</head>
<body>
 <div id="box"
style="
width: 500px; 
height:500px; 
border: 2px solid red;
position:relative;
">
<div id="circle" 
    style="
    width:10px;
    height: 10px; 
    background-color: #000;
    border-radius: 50%;
    position: absolute;
    "></div>
 </div>    
<script>
//mousemove Event
const box =document.getElementById("box");
const circle=document.getElementById("circle");
box.addEventListener("mousemove", (event)=>{
    //console.log(event);
    circle.style.top=`${event.clientY}px`;
    circle.style.left=`${event.clientX}px`;
});

</script>
</body>
</html>

 

 

 

예4)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>5.이벤트 핸들러(Event Handler)</title>
</head>
<body>
<script>
 window.addEventListener('resize', ()=>{
    document.body.innerText=
    `현재 창 크기는 ${window.innerWidth} x ${window.innerHeight}`;
 })
</script>
</body>
</html>

 

 

 

 

 

 

 

 

6.이벤트 버블링, 이벤트 위임

 

 

 

 

 

 

예1)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>6.이벤트 버블링, 이벤트 위임</title>
<style>
    div, ul, li{
        border:5px solid #000;
        padding: 50px;
        font-size: 2.2rem;
        font-weight: 600;    
    }
    #box{
        background-color: green;
    }
    #list{
        background-color: orange;
    }
    #color{
        background-color: yellow;
    }
</style>    
</head>
<body>
<div id="box">
    <ul id="list">
        <li id="color">Red</li>
    </ul>
</div>
<script>
const box=document.getElementById("box");
const lit=document.getElementById("list");
const color=document.getElementById("color");

document.body.addEventListener("click",()=>{
    console.log("1.body");
})
box.addEventListener("click",()=>{
    console.log("2.div");
})
lit.addEventListener("click",()=>{
    console.log("3. ul");
})
color.addEventListener("click",()=>{
    console.log("4. li");
})

</script>    
</body>
</html>

 

 

 

예2)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>6.이벤트 버블링, 이벤트 위임</title>
<style>
    div, ul, li{
        border:5px solid #000;
        padding: 50px;
        font-size: 2.2rem;
        font-weight: 600;    
    }
    #box{
        background-color: green;
    }
    #list{
        background-color: orange;
    }
    #color{
        background-color: yellow;
    }
    #txt{
        width: 100%;
        height: 50px;
    }
</style>    
</head>
<body>
<div id="box">
    <input id="txt" type="text" />
</div>
<script>
const box=document.getElementById("box");
const txt=document.getElementById("txt");

document.body.addEventListener("focusin",()=>{
    console.log("focus -1.body");
})
box.addEventListener("focusin",()=>{
    console.log("focus - 2.div");
})
txt.addEventListener("focusin",(event)=>{
    event.stopPropagation();
    console.log("focus- 3.input");
})



document.body.addEventListener("blur",()=>{
    console.log("blur -1.body");
})
box.addEventListener("blur",()=>{
    console.log("blur - 2.div");
})
txt.addEventListener("blur",()=>{
    console.log("blur- 3.input");
})



</script>    
</body>
</html>

 

 

 

 

예3)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>6.이벤트 버블링, 이벤트 위임</title>
<style>
    div, ul, li{
        border:5px solid #000;
        padding: 50px;
        font-size: 2.2rem;
        font-weight: 600;    
    }
    #box{
        background-color: green;
    }
    #list{
        background-color: orange;
    }
    #list li{
        cursor: pointer;        
    }
    #red{
        background-color: red;
    }
   #blue{
        background-color: blue;
    }
    #green{
        background-color: green;
    }
    #pink{
        background-color: pink;
    }  
    #list .on{
          background-color: yellow;
    }  
</style>    
</head>
<body>
<div id="box">
    <ul id="list">
        <li id="red" class="on"><a href="#">Red</a></li>
        <li id="blue"><a href="#">Blue</a></li>
        <li id="green"><a href="#">Green</a></li>
        <li id="pink"><a href="#">Pink</a></li>
    </ul>
</div>
<script>
const lit=document.getElementById("list");
const colors=lit.children;

function clickHandler(event){    
    //console.log("target : ", event.target);
    //currentTarget 여기서 ul 을 가리킨다.
    //console.log("currentTarget:", event.currentTarget);
    let target=event.target;    
    if(target.tagName==="A"){   
        event.preventDefault();    
        target=target.parentElement;  //a  인경우 부모인 li 로  변경
    }else if(target===event.currentTarget){
        //여기서 ul과 같다면 리턴
        return;
    }
    

    for(c of colors){
        c.classList.remove("on");
    }

    target.classList.add("on");
}

// document.getElementById("red").addEventListener("click", clickHandler);
// document.getElementById("blue").addEventListener("click", clickHandler);
// document.getElementById("green").addEventListener("click", clickHandler);
// document.getElementById("pink").addEventListener("click", clickHandler);



// const lis=document.querySelectorAll("li");
// for(li of lis){
//     li.addEventListener("click", clickHandler);
// }


//이벤트 위임 
document.getElementById("list").addEventListener("click", clickHandler);




</script>    
</body>
</html>

 

 

 

 

 

 

 

소스 :  https://github.com/braverokmc79/javascirpt-dom-event

 

 

 

 

 

about author

PHRASE

Level 60  라이트

양심은 개인이 자기 보존을 위해 개발한, 사회의 질서를 지키는 수호신이다. -서머셋 모음

댓글 ( 4)

댓글 남기기

작성