728x90
반응형
728x90
반응형
<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
</head>
<body>
    
</body>
</html>
<script>
    // promise : 비동기 처리를 위해 ES6부터 지원되는 비동기 함수
    // promise 생성자 함수는 비동기 처리를 수행할 콜백 함수(executor 함수)를 인수로 전달받음
    // executor는 resolve, reject라는 두 개의 함수르 인수로 전달받음
    // promise는 생성되는 순간 바로 executor 를 실행함(중요!)
    // promise는 실행이 끝난 promise 객체를 반환함
    // Promis 상태 -
    // 1) prnding : 비동기 처리가 아직 수행되징 않은 상태로, 프로미스 생성 직후 상태
    // 2) fulfiled : 비동기 처리가 수행된 상태(성공)로, resolve가 호출된 상태
    // 3) rejected : 비동기 처리가 수행된 상태(실패)로 , reject가 호출도니 상태

    // 생성자. producer - promise를 생성하는 쪽
    // const promise = new Promise((resolve, reject) =>{
    //     if(true){// 비동기 처리가 성공했을 시
    //         resolve('result');
    //     }
    //     else {// 비동기 처리 실패 시
    //         reject('failure reason')
    //     }
    // });


    // Consumer 소비자, Promise 객체(의 내부 함수)를 소비하는 쪽    
    // Promise의 후속처리 메서드
    // 1) then
    //      - 두 개의 콜백 함수를 인수로 전달받음
    //      - Promise가 fulfiled된 상태 (resolve 호출) Promise의 처리 결과를 인수로 받음
    //      - Promise가 rejected된 상태 (reject 호출) Promise 의 에러를 인수로 받음
    // const successedPromise = new Promise ((resolve, reject)=>{
    //     resolve('성공했다');
    // }); 
    
    // const faliededPromise = new Promise ((resolve, reject)=>{
    //     reject('실패했다');
    // });
    // faliededPromise.then( 
    //     value => { console.log('val: ', value);}, 
    //     e => { console.log('e: ', e);}
    // );

    // // 2) catch
    // //      - 한 개의 콜백 함수를 인수로 전달받음
    // //      - Promise가 rejected 된 상태의 경우만 호출되며, Promise의 에러를 인수로 받음
    // //      - then과 동일하게 동작함
    // // 
    
    // new Promise((res, rej)=> rej(new Error('실패되었음')))
    // .catch((e)=> { console.log(e);
    // });
    
    
    // // 3) finally
    // //      - 한 개의 콜백 함수를 인수로 전달받음
    // //      - Promise성공 실패 상관없이 호출됨
  
    // new Promise((resolve, reject) => {
    //     // resolve('성공입니다.!');
    //     reject('실패입니다.!');

    // }).finally(() => {
    //     console.log('마지막입니다.');
    // });


    // // Promise를 사용한 예외처리
    // let errorPromise = new Promise((resolve, reject) =>{
    //     setTimeout(()=>{
    //         try{
    //             throw new Error('에러났다!!!!!!!!');
    //             resolve();
    //         }catch(e){
    //             reject(e);
    //         }
    //     },3000)
    // });

    // errorPromise.then(
    //     value => {},
    //     error => {
    //         console.log('에러가 나버렸다');
    //         console.log('에러: ', error)
    //     }
    // );




    //     let testPromise = new Promise((resolve, reject) =>{
    //         setTimeout(()=>{resolve(f1)},1000)
    //     });
    //     testPromise.then(
    //         value => {value()},
    //         error => {}
    //     ).then(
    //         value => {f2()},
    //         error => {}
    //     ).then(
    //         vlaue => {f3()},
    //         error => {}
    //     )

    //     function f1(){
    //         console.log('f1이 실행되었음');
    //     }
    //     function f2(){
    //         console.log('f2이 실행되었음');
    //     }
    //     function f3(){
    //         console.log('f3이 실행되었음');
    //     }


    const data1 = () => new Promise(resolve => setTimeout(()=> resolve(3),3000))
    const data2 = () => new Promise(resolve => setTimeout(()=> resolve(2),2000))
    const data3 = () => new Promise(resolve => setTimeout(()=> resolve(1),1000))
    // const data1 = () => new Promise((_, rej) => setTimeout(()=> rej(3),3000))
    // const data2 = () => new Promise((_, rej) => setTimeout(()=> rej(2),2000))
    // const data3 = () => new Promise((_, rej) => setTimeout(()=> rej(1),1000))
    
    Promise.all([data1(), data2(), data3()]) // 마지막 처리가 끝나면 동시에 출력
    .then(console.log)
    .catch(console.log);
    
    Promise.race([data1(), data2(), data3()]) // 제일 빨리 처리한것만 출력
    .then(console.log)
    .catch(console.log);
    

    setTimeout(() => console.log('10'),0);
    Promise.resolve()
        .then(()=> console.log(20))
        .then(()=> console.log(30));
    





    const promises = [];
    data1().then( value => {
        promises.push(value);
        return data2()
    })
    .then(value => {
        promises.push(value);
        return data3()
    })
    .then(value => {
        promises.push(value);
        console.log(promises)
    })






</script>
728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

js 시계 + 타이머 만들기  (0) 2023.01.03
setTimeout / setInterval 사용 요약  (0) 2023.01.03
addEventListener 활용2  (0) 2023.01.03
addEventListener 활용1  (0) 2023.01.03
js 기초6  (0) 2023.01.03
728x90
반응형

HTML코드

<!DOCTYPE html>
<html lang="ko">
<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>전자시계</title>
    <script src="2_Clock.js" defer></script>
</head>
<body>
    <section>
        <div id="click-container">
            <div id="date-now"><i>현재날짜: </i><span></span></div>
            <div id="time-now"><i>현재시간: </i><span></span></div>
        </div>
        <div id="timer-container">
            <div>
                <div id="timer"><span>00:00:00</span></div>
                <button>시작/재시작</button>
                <button>일시정지</button>
                <button>초기화</button>
            </div>
        </div>
    </section>
</body>
</html>
300x250
반응형

js 코드

const dateNow = document.querySelector('#date-now > span'); //현재 날짜 부분
const timeNow = document.querySelector('#time-now > span'); //현재 시간 부분
const timer = document.querySelector('#timer > span'); //타이머 시간 부분
const btns = document.getElementsByTagName('button'); //모든 버튼
const startBtn = btns[0]; //시작버튼
const stopBtn = btns[1];  //중지버튼
const clearBtn = btns[2]; //초기화버튼
const timerStatus = { RUNNING: true, STOP: false }; //enum처럼 상태 객체를 만들기
let nowStatus = timerStatus.STOP; //타이머의 상태를 저장하는 변수 (기본값: STOP)
let timerID = ""; // 1초마다 타이머를 갱신시킴
//0.2초마다 날짜를 갱신

setInterval(date_setting, 200);


// Start 버튼을 눌렀다면
startBtn.onclick = () => {
    //타이머 id를 받아오고, 1초마다 타이머가 시작하도록 함
    nowStatus = timerStatus.RUNNING;
    if(timerID === ""){
        timerID = setInterval(timer_setting, 100);
    }
}

stopBtn.onclick = () => {
    if(timerID !== ""){
        nowStatus = timerStatus.STOP;
    }
}

clearBtn.onclick = () => {
    //timerID가 존재하면(빈문자열이아니면) interval을 중지하고, 그게 아니면 timerID를 그대로(빈문자열로) 둔다
    if(timerID !== ""){
        clearInterval(timerID);
        timerID = ""; //timerID를 초기화한다
        timer.textContent = "00:00:00"; //문자열을 처음으로 돌린다
    }    
}


//현재 날짜 정보를 설정하는 함수
function date_setting(){
    //날짜를 설정하기 위한 Date객체를 생성한다
    const date = new Date();
    //날짜 문자열을 생성
    const dateString = `${date.getFullYear()}-${format_setting(date.getMonth() + 1)}-${format_setting(date.getDate())}`;
    //현재 날짜 부분을 실제 날짜로 변경
    dateNow.textContent = dateString;
    //시간 문자열을 생성
    const timeString = `${format_setting(date.getHours())}:${format_setting(date.getMinutes())}:${format_setting(date.getSeconds())}`;
    timeNow.textContent = timeString;
}

//status: 현재 동작중인지, 정지상태인지 설정하는 상태 변수
function timer_setting(){
    if(nowStatus === timerStatus.STOP){ return; }

    let timerNowString = timer.textContent; //현재 진행된 타이머 시간
    let times = timerNowString.split(':'); // ':'으로 문자열을 나눈다
    let hour = +times[0]; //시
    let min = +times[1]; //분
    let sec = +times[2]; //초
    sec++; //1초 증가시킴
    if(sec >= 60){  //1초 증가했는데 60초가 되었다?
        min++;      //1분 증가시킴
        sec = 0;    //초를 0으로 돌림
    }
    if(min >= 60){  //1분 증가했는데 60분이 되었다?
        hour++;     //1시간 증가시킴
        min = 0;    //분을 0으로 돌림
    }
    if(hour >= 24){ //1시간 증가했는데 24시간이 되었다?
        hour = 0;   //hour를 0으로 돌림
        clearInterval(timerID); //타이머를 중지시킴
    }
    //1초가 지난 현재 타이머 시간을 문자열로 생성
    const timerSting = `${format_setting(hour)}:${format_setting(min)}:${format_setting(sec)}`;
    //타이머 시간 표시 부분에 문자열을 설정
    timer.textContent = timerSting;
}

//날짜나 시간 형식을 00:00:00 형태로 만들어주기 위한 포맷 형식
function format_setting(data){ //data -> 월, 일, 시, 분, 초 중에 하나가 들어옴 (string)
    // data 를 문자열로 바꿧을 때 한 글자면 앞에 0을 붙여서 반환시킨다.
    return data.toString().length < 2 ? '0' + data : data;
}












728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

promise  (0) 2023.01.03
setTimeout / setInterval 사용 요약  (0) 2023.01.03
addEventListener 활용2  (0) 2023.01.03
addEventListener 활용1  (0) 2023.01.03
js 기초6  (0) 2023.01.03
728x90
반응형
<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
    <script>
        // JS는 기본 싱클 스레드로 동작함(single thread)
        // 따라서, JS는 두 가지 이상의 일(task)를 동시 실행할 수 없음.
        // 타이머 함수 (setTimeout, setInterval) -> JS가 처리하는게 아니라, web 에서 처리함. 따라서 병렬로 작업함
        // setTimeout: 일정시간 후에 한번 전달받은 함수를 실행함(한번동작)
        // setInterval: 일정시간마다 전달받은 함수를 실행(반복동작)
        //          - handler : 내가 실행하고 싶은 함수
        //          - timeout : 일정 시간 이후 실행할 초(ms, 1/1000)
        //                  - 값을 지정하지 않을 시, 기본값 0이 지정됨 최소4ms지난 후 실행됨.
        //          - ...arguments : 실행하고 싶은 함수에 전달할 인자들을 순서대록 작성


        // 
        const id = setTimeout(print, 1000, '실행했어', 300);
        clearTimeout(id);//작업 설정한 id를 전달하여 예약된 작업을 취소

        setTimeout(() =>{
            console.log('함수가실행됬다')
        },2000);

        function print(message, number){
            console.log(message)
            console.log(number)
        }



        const intwervalId = setInterval(print2, 500);
        setTimeout(()=>{
            clearInterval(intwervalId)

        }, 1500);

        function print2(){
            console.log('반복작업1');
        };

        
    </script>
</head>
<body>
    
</body>
</html>
728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

promise  (0) 2023.01.03
js 시계 + 타이머 만들기  (0) 2023.01.03
addEventListener 활용2  (0) 2023.01.03
addEventListener 활용1  (0) 2023.01.03
js 기초6  (0) 2023.01.03
728x90
반응형
<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
    <style>
        #text_container{
            background-color: beige;
        }
    </style>
</head>
<body>
    <div id="input_container">
        <input type="text" placeholder="문자를 입력해보세요">
        <button>입력</button>
    </div>
    <div id="text_container">
        
    </div>


    <script>
        // 버튼을 눌렀을 시, 혹은 엔터를 입력했을 시 텍스트 div을 넣어줄부모 컨테이너
        let textContainer = document.getElementById('text_container');
        //입력 버튼을 가져옴
        let inputButton = document.querySelector('button');
        //입력 태그(텍스트창)
        const inputTag = document.querySelector('input');
        // 입력 버튼을 클릭했을 떄 실행할 동작을 설정
        inputButton.addEventListener('click', appendText);
        
        //키가 눌렸다가 때졌을 경우 이벤트 등록
        inputTag.onkeyup = e => {
            // 눌려진 키가 Enter가 아니라면
            if(e.key !== 'Enter'){
                return; //함수 종료
            }
            appendText(); //자식으로 텍스트 div를 추가한다
        }
        
        
        // 부모 컨테이너 div 에 자식으로서 텍스트를 추가해주는 함수
        function appendText(){
            // 현재 부모 컨테이너의 자식 개수를 받아온다.
            const chileCount = textContainer.childElementCount;
            let div = document.createElement('div');//div 태그를 가진 노드 생성
            div.className = '내용';
            // text설정한다 -> '행번호 : inputTag의 내용'
            // 따라서 -> 'childCount + 1 : inputTag.value'
            div.textContent = `${chileCount + 1} : ${inputTag.value}`;//해당 div의 내용을 설정한다.
            textContainer.appendChild(div);
            //현재 줄에 넣을 삭제버튼 생성
            const removeBtn = document.createElement('button');
            removeBtn.innerText = '삭제';
            div.appendChild(removeBtn);
            //삭제 버튼을 눌렀을 때, div 를 제거함
            removeBtn.addEventListener('click', () =>{
                // 현재 div의 번호를 받아온다.
                let divNumber = +div.textContent.split(':')[0];
                console.log(divNumber)
                
                // for (let index = divNumber; index < divChildren.length; index++) {
                //     const element = array[index];
                    
                // }
                
                // for (let index = divNumber + 1; index < divChildren.length; index++) {
                //     // 현재 index의 div가 가지고있는 글자를 전부 가져온다
                //     let content = divChildren.item(index).innerHTML;
                //     divChildren.item(index).textContainer = `${index - 1}: ${content.split(':')[1]}`; // 텍스트 내용 부분만 가져온다.(번호뺴고)                    
                // }


                // div를 삭제한다.
                div.remove();
            });    
            inputTag.value = '';// input태그 내용을 초기화  
        } 
     
        
        
    
        
    </script>
</body>
</html>
300x250

 

실행창

반응형

 

728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

js 시계 + 타이머 만들기  (0) 2023.01.03
setTimeout / setInterval 사용 요약  (0) 2023.01.03
addEventListener 활용1  (0) 2023.01.03
js 기초6  (0) 2023.01.03
js 기초5  (0) 2023.01.01
728x90
반응형
<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
    <script src="inputEvent.js" defer></script>
    
    <style>
        .box{
            width: 100px;
            height: 100px;
            background-color: #FFF700;
            border: 5px solid red;
            cursor : pointer;
        }
    </style>

</head>
<body>
    <div class="box"></div>
</body>
</html>
300x250
반응형
const box = document.querySelector('.box');
const initMousPos = {x:0, y:0};//리터럴 객체생성방법 // 마우스 드래그 시작 지점의 위치
// functioninitMouserPos(){
//     this.x = 0;
//     this.y = 0;
// }
const offset = {x : 0, y : 0}; //이동할 거리
// mousemove시 실행할 move함수
const move = function(event){
    // 이동할 거리 = 현재 (드래그 진행 시점)의 마우스 위치 - (드래그 시작 지점의 마우스 위치)
    offset.x = event.clientX - initMousPos.x;
    offset.y = event.clientY - initMousPos.y;
    // translate3d는 GPU를 사용하기 떄문에 top, left 속성을 변경하는 것보다 처리 속도가 빠름
    // top, left는 레이아웃에 영햘을 줌
    box.style.transform = `translate3d(${offset.x}px, ${offset.y}px,0)`;
};
// mousedown : 마우스가 눌렸다(클릭아님)
// mousedown 이벤트 발생 시, 드래그 시작 시점의 마우스 포인터 좌표(event.clientX 와 clientY)를 저장해 둡니다.
// 
box.addEventListener('mousedown', event =>{
    initMousPos.x = event.clientX - offset.x;
    initMousPos.y = event.clientY - offset.y;
    // mousedown 이벤트가 발생한 상태에서 mousemove 이벤트가 발생하면 box를 이동시키는 move를 실행
    document.addEventListener('mousemove', move);
});
// mouseup : 마우스를 떄는 이벤트(클릭 아님)가 발생하면 move 이벤트를 하면 안되므로 제거해준다
document.addEventListener('mouseup', () =>{
    document.removeEventListener('mousemove', move);
});


 

 

마우스로 클릭 후 이동 가능한 네모난 상자만들기

728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

setTimeout / setInterval 사용 요약  (0) 2023.01.03
addEventListener 활용2  (0) 2023.01.03
js 기초6  (0) 2023.01.03
js 기초5  (0) 2023.01.01
js 정규식 연습1  (0) 2023.01.01
728x90
반응형
<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
    <script src="index.js"></script>
</head>
<body>
    <input type="text" id="user" value="koreait">
    <div class="welcome box">Hello world</div>
    <ul id="users">
        <li id="1" data-user-id="1234">홍길동</li>
        <li id="2" data-user-id="5678">김나나</li>
    </ul>
    



    <script>
        const userInput = document.getElementById('user');
        // 속성값 취득
        const userInputVal = userInput.getAttribute('value')
        console.log(userInputVal);
        // 속성값 변경
        userInput.setAttribute('value', 'webstudy');
        // 속성값 존재 확인
        console.log('id 속성 존재? >>',userInput.hasAttribute('id'));
        // 속성값 삭제
        userInput.removeAttribute('value');


        userInput.value = 'test';
        console.log(userInput.value);
        console.log(userInput.attributes);
        console.log(userInput.attributes.id.value);
        console.log(userInput.attributes.type.value);
        // console.log(userInput.attributes.value.value);
        for(let attr of userInput.attributes){
            console.log(attr);
        }

        const users = [...document.getElementById('users').children];
        users.forEach( user => {
            console.log(user.dataset.userId);
        });
        const user5678 = users.find( user => { return user.dataset.userId === '5678'});
        console.log(user5678);

        document.getElementsByTagName('li').item(0).style.color = 'red';
        document.getElementsByTagName('li').item(0).style.backgroundColor = 'black';
        document.getElementsByTagName('li').item(0).style.lineHeight = '3';
        document.getElementsByTagName('li').item(0).style['line-height'] = '1';
        document.getElementsByTagName('li').item(0).style['height'] = '100px';
        console.log(document.getElementsByTagName('li').item(0).style.color);



        const box = document.querySelector('div');
        console.log(box.className);
        box.className = box.className.replace('welcome', 'hello');
        box.classList.add('welcome');
        box.classList.remove('box');
        box.classList.replace('welcome','come');
        box.classList.toggle('box',true); // 있으면 삭제 / 없으면 생성(true/false 가능)
        box.classList.contains('come');



        console.log(box.classList);







    </script>
</body>
</html>
300x250
const aTag = document.getElementsByTagName('a').item(0);
// 복제된 a 태그에 class 속성을 부여한다.
aTag.classList.add('site');
// a태크를 넣을 부모요소 div를 가져온다.
const container = document.getElementById('container');
for(let i = 1; i <= 5; i++){
        // a 태그 노드를 복제한다.
        const aTagClone = aTag.cloneNode();
        // 복제된 a 태그의  href 속성 내가 원하는 걸로 변경한다.
        aTagClone.setAttribute('href','https://search.naver.com/search.naver?where=nexearch&query=test'+i)
        // 복제된 a 태그의 내부 텍스트를 변경한다.
        aTagClone.textContent = 'test'+i;
        //  홀수번째 복제테그에는 color와 text-dacoration style을 추가한다.
        if(i % 2 !== 0){
                aTagClone.style.color = 'rgb(255,0,0)';
                aTagClone.style.textDecoration = 'none';
        }
        // div의 자식으로서 추가한다.
        container.appendChild(aTagClone);
}
// div container의 마지막 자식 요소에 font-size스타일 설정
container.lastElementChild.style.fontSize = '30px';
// h1테그를 생성한다
const h1Tag = document.createElement('h1');
// h1 태그의 텍스트를 변경한다
h1Tag.textContent = '이동링크 페이지1';
// 부모 div태그의 가장 첫 a 태그 전 위치에 h1 태그를 삽입한다.
container.insertBefore(h1Tag, aTag);
container.insertAdjacentHTML('afterbegin','<h1>이동링크 페이지2</h1>');














반응형
<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
    <style>
        body{
            background-color: beige;
        }
        .box{
            width: 100px;
            height: 200px;
            background-color: chocolate;
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <div class="box">BOX</div>
    <script>
        const box = document.querySelector('.box');
        // style 프로퍼티는 인라인 스타일만 반환...
        // box.style.backgroundColor = 'red';
        // ComputedStyle은 요소 노드에 적용되어있는 모든 스타일을 종합해서 가져옴
        // 링크스타일, 인라인, JS에 설정한 몯느 스타일이 적용되어진 최종 스타일
        const computedBox = window.getComputedStyle(box);
        let background = computedBox.backgroundColor;
        // rgb(?, ?, ?)
        // setInterval(() => {
            let strtIndex = background.indexOf('(');
            background = background.substring(strtIndex + 1 , background.length -1);
            background = background.split(',');
            let r = background[0].trim();
            let g = background[1].trim();
            let b = background[2].trim();
            box.style.backgroundColor = `rgb(${r}, ${g}, ${10 + b})`;

        // });
        // box.style.backgroundColor = background;
        // box.style.width = '500px';
        // console.log(computedBox.widows);
        // console.log(computedBox.backgroundColor);
        // console.log(computedBox.border);
        // console.log(computedBox.height);

    </script>
</body>
</html>
728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

addEventListener 활용2  (0) 2023.01.03
addEventListener 활용1  (0) 2023.01.03
js 기초5  (0) 2023.01.01
js 정규식 연습1  (0) 2023.01.01
js 정규식  (2) 2023.01.01
728x90
반응형
"use strict"


"use strict"
function a(){
    console.log(a);

}

console.log(a);



// async, defer도 아닌 script태그 : 동기적. HTML문서에서 순서대로 차례대로 실행
//          JS파일 다운로드가 끝나면 순서대로 실행함
// async : 비동기적, script 태그 순서와 상관없이 로딩이 완료된 JS부터 실행됨
//      순서가 보장되지 않음. DOM요소와 상관없거나, 최대한 빨리 실행해야하는 JS파일에 설정
// defer : 비동기적, async와 같이 다운로드는 비동기적으로 진행하지만, DOM요소가 전부 로딩이 끝나면 실행
//      DOM요소를 제어해야하는 JS파일에 설정
// 1) 문서 노드(dovument node) : DOM 트리의 최상위에 존재하는 ROOT노드. document 객체를 가리킴
// 2) 요소 노드(element node) :
// 3) 속성 노드(attribute node) : HTML 요소의 속성(어트리뷰트)를 가리키는 객체
// 4) 텍스트 노드(text node) : HTML 요소의 텍스트를 가리키는 객체 (요소 노드의 자식노드)
// Node의 상속 관계
// OBJECT - Event - Node - (Document, Element, Attr, CharacterData)
// Document - HTMLDocument
// Element - HTMLElement - ~~~
// CharacterData - (Text, Comment)


// const element = document.getElementById('banana');
// console.log(element);
// element.style.color = 'blue';





// 스프레드 문법
// const elements = document.getElementsByTagName('li');
// let a, b, c = [...elements].forEach

// Array.from(elements).forEach(el => {
//     el.style.fontSize = '400px';
// });
// for(let el of elements){
//     el.style.fontSize = '400px';
// }
// for(let i = 0; i < elements.length; i++){
//     elements.item(i).style.fontSize = '400px';
// }

// elements.item(0).style.color = 'red';
// console.log('li들 : ', elements);
// console.log('li의 첫번째요소 : ', elements.item(0));

// [...document.getElementsByClassName('fruit2')].forEach(el => {
//     el.style.color = 'green';
// });

// const select = document.querySelectorAll('body > ul li');
// select.forEach(x => {
//     x.style.color = 'green';
// });





const apple = document.querySelector('.apple');
console.log(apple.matches('#fruit > li.apple'));
console.log(apple.matches('#fruit > li.banana'));


// 공백노드 포함. 텍스트 노드 포함해서 가져옴
const fruits = document.getElementById('fruit');
console.log('childNodes 자식들 >> ');
console.log(fruits.childNodes);
// 요소만 가져옴.  텍스트 노드 포함하지 않음
console.log('children 자식들 >> ');
console.log(fruits.children);

// firstChild: childNodes 의 첫번째 노드를 가져옴. 따라서 테그슽노드 포함
console.log('firstChild 자식들 >> ');
console.log(fruits.firstChild);

// firstElementChild: children 첫번째 노드를 가져옴. 따라서 텍스트 노드 포함안함
console.log('firstElementChild 자식들 >> ');
console.log(fruits.firstElementChild);

// 부모 노드 탐색

let lies = document.getElementsByTagName('li');
[...lies].forEach(li => {
    console.log('현재노드>> ', li);
    console.log('parentNode >> ', li.parentNode);
    console.log('parentElement >> ', li.parentElement);
});

console.log("형제 노드 탐색 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
// 형제 노드 탐색
let lies1 = document.getElementsByTagName('li');
[...lies1].forEach(li => {
    console.log('현재노드>> ', li);
    console.log('nextSibling >> ', li.nextSibling);
    console.log('nextElementSibling >> ', li.nextElementSibling);
    li.textContent = '안녕하세요.';
    console.log('현재 li태그의 텍스트: ', li.textContent);
});










// 크로스 사이트 스크립팅 공격(XSS)에 취약함...
// HTML 새니티제이션: XSS 공격 방어 DOMPurify 라이브러리 사용
// DOMPurify.sanitize(<script>alert("You hacked!")</script>)
// const welcome = document.getElementById('welcome');
// [...welcome.getElementsByTagName('span')].forEach(span => {
//     span.style.color = 'blue';
// });
// // welcome.textContent = '<span>test</span>';
// welcome.innerText = '<span>test</span>';
// welcome.innerHTML = '<script>alert("You hacked!")</script>';
// console.log(welcome.textContent); // Node에 존재하는 텍스트 부분
// console.log(welcome.innerText); // 요소에 존재하는 텍스트 부분
// console.log(welcome.innerHTML); // 노드 내부 HTML으로 작성된 텍스트

let fruit = document.getElementById('fruit');
fruit.innerHTML += '<li class="melon">Melon</li>';
document.getElementsByClassName('melon').item(0).style.color = 'green';

fruit.insertAdjacentHTML('afterbegin','<p>afterbegin</p>');
fruit.insertAdjacentHTML('beforebegin','<p>beforebegin</p>');
fruit.insertAdjacentHTML('afterend','<p>afterend</p>');
fruit.insertAdjacentHTML('beforeend','<p>beforeend</p>');

let newNode = document.createTextNode('새로 생성한 텍스트 노드');
fruit.appendChild(newNode);

fruit.replaceChild(newNode, fruit.firstElementChild);

// let welcome = document.getElementById('welcome');
// for(element of fruit.childNodes){
//     welcome.appendChild(element.childNode(true));
// }











728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

addEventListener 활용1  (0) 2023.01.03
js 기초6  (0) 2023.01.03
js 정규식 연습1  (0) 2023.01.01
js 정규식  (2) 2023.01.01
js 연습2  (0) 2023.01.01
728x90
반응형
//정규식 연습입니다..
//https://school.programmers.co.kr/learn/courses/30/lessons/72410
// 1단계 new_id의 모든 대문자를 대응되는 소문자로 치환합니다.
// 2단계 new_id에서 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.)를 제외한 모든 문자를 제거합니다.
// 3단계 new_id에서 마침표(.)가 2번 이상 연속된 부분을 하나의 마침표(.)로 치환합니다.
// 4단계 new_id에서 마침표(.)가 처음이나 끝에 위치한다면 제거합니다.
// 5단계 new_id가 빈 문자열이라면, new_id에 "a"를 대입합니다.
// 6단계 new_id의 길이가 16자 이상이면, new_id의 첫 15개의 문자를 제외한 나머지 문자들을 모두 제거합니다.
//      만약 제거 후 마침표(.)가 new_id의 끝에 위치한다면 끝에 위치한 마침표(.) 문자를 제거합니다.
// 7단계 new_id의 길이가 2자 이하라면, new_id의 마지막 문자를 new_id의 길이가 3이 될 때까지 반복해서 끝에 붙입니다.
// 최종적으로 바꾼 아이디를 반환하세요

function kakao(s){
    s = s.toLowerCase(); // 1단계
    s = s.replace(/[^a-z0-9-_.]/g,''); //2단계
    s = s.replace(/\.{2,}/g, '\.'); //3단계
    s = s.replace(/^\.|\.$/g,''); //4단계
    s = s.length === 0 ? 'a' : s; //5단계
    s = s.length >= 16 ? s.substring(0, 15) : s; //6단계
    s = s.replace(/\.$/g, ''); //6단계
    s = s.length <= 2 ? s + s.slice(-1).repeat(3 - s.length) : s; //7단계
    console.log(s)
    return s;
}
console.log( kakao("...!@BaT#*..y.abcdefghijklm") == "bat.y.abcdefghi");
console.log( kakao("z-+.^.") == "z--" );
console.log( kakao("=.=") == "aaa" );
console.log( kakao("123_.def") == "123_.def" );
console.log( kakao("abcdefghijklmn.p") == "abcdefghijklmn" );
728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

js 기초6  (0) 2023.01.03
js 기초5  (0) 2023.01.01
js 정규식  (2) 2023.01.01
js 연습2  (0) 2023.01.01
js 기초4  (2) 2023.01.01

+ Recent posts

728x90
반응형
">