본문 바로가기
웹 개발

22. 자바스크립트 다양한 출력들3

by 곽정우 2024. 4. 17.

 

1. String 객체

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>String객체</title>
</head>
<body>
    <h2>String 객체</h2>
    <script>
        const str1 = '안녕하세요. JavaScript';
        const str2 = new String('안녕하세요. JavaScript');

        console.log(str1 == str2);
        console.log(str1 === str2);
        console.log(typeof(str1));
        console.log(typeof(str2));

        // length: 문자열의 길이를 반환
        console.log(str1.length);

        // indexOf(): 특정 문자나 문자열이 처음으로 등장하는 위치를 인덱스로 반환
        console.log(str1.indexOf('J'));
        console.log(str1.indexOf('Java'));
        console.log(str1.indexOf('java')); // 못 찾으면 -1 출력
        console.log(str1.indexOf('a'));
        console.log(str1.lastIndexOf('a'));

        // charAt(): 특정 문자열에서 전달 받은 인덱스에 위치한 문자를 반환
        console.log(str1.charAt('7'));

        // includes(): 특정 문자열에서 전달 받은 문자열이 포함되어 있는지 여부를 반환
        console.log(str1.includes('Java'));
        console.log(str1.includes('java')); // 못 찾으면 false 출력

        // substring(): 전달 받은 시작 인덱스부터 종료 인덱스 직전까지의 문자열을 추출
        console.log(str1.substring(7));
        console.log(str1.substring(7, 11));


        // replace(): 원본 문자열의 일부를 전달 받은 문자열로 치환
        console.log(str1.replace('안녕하세요', 'Hello'));

        // split(): 구분자를 기준으로 나눈 후 나뉘 문자열을 하나의 배열에 저장
        const str3 = '김사과, 오렌지, 반하나, 이메론, 베이리, 체리';
        const students = str3.split(',');
        console.log(students);

        for(let i in students){
            console.log(i, students[i]);
        }
        console.log('--------');

        // trim(): 문자열의 앞 뒤 공백을 제거
        const str4 = '          JavaScript          ';
        console.log(`🤩${str4}😀`);
        console.log(`🤩${str4.trim()}😀`);

        // toUpperCase(), toLowerCase(): 문자열을 모두 대, 소문자로 변환
        console.log(`${str4.trim().toUpperCase()}🤩`);
        console.log(`${str4.trim().toLowerCase()}🤩`);
    </script>
</body>
</html>

2. Date 객체

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Date객체</title>
</head>
<body>
    <h2>Date 객체</h2>
    <script>
        console.log(new Date());
        console.log(new Date(24, 10, 11)); // 1924, 11, 11
        const current_time = new Date(2024, 3, 17, 9, 51, 0);
        console.log(current_time);
        console.log(`현재 연도: ${current_time.getFullYear()}`);
        console.log(`현재 월: ${current_time.getMonth()}`);
        console.log(`현재 일: ${current_time.getDate()}`);
        console.log(`현재 시간: ${current_time.getHours()}`);
        console.log(`현재 분: ${current_time.getMinutes()}`);
        console.log(`현재 초: ${current_time.getSeconds()}`);
    </script>
</body>
</html>

 


3. 폼(form) 개체

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>폼객체</title>
</head>
<body>
    <h2>폼 객체</h2>
    <form action="/regist" name='frm1' id ='frm1'>
        <input type="text" name='userid' id ='userid' placeholder="아이디를 입력하세요:"><br>
        <input type="password" name='userpw' id ='userpw' placeholder="비밀번호를 입력하세요:">
    </form>

    <form action="/search" name='frm2' id ='frm2'>
        <input type="search" name='search' id ='search' placeholder="검색어를 입력하세요:"> <button type="button" onclick="sendit()">확인</but>
    </form>

    <script>
        const frm1 = document.frm1;
        console.log(frm1);
        console.log(frm1.userid.placeholder);
        document.getElementById('userid').value = 'apple';
        document.forms['frm1'].elements['userpw'].value = '1004';

        // frm2의 search에 있는 placeholder를 콘솔에 출력
        const frm2 = document.frm2;
        console.log(frm2.search.placeholder);
        frm2.search.value = '코리아IT아카데미'

        // frm2의 search를 forms 컬렉션의 인덱스로 찾아 search 요소에 '코리아IT아카데미'를 입력
        frm2.search.value = '코리아IT아카데미'
        
        function sendit(){
            alert('확인을 눌렀어요')

        }
    </script>

</body>
</html>

4.  setTimeout

3초 뒤에 alert 발생

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>setTimeout</title>
</head>
<body>
    <h2>setTimeout</h2>
    <script>
        const hello = function(){
            alert('안녕하세요. JavaScript!');
        }

        const st = setTimeout(hello, 3000); //3초
        clearTimeout(st);
    </script>
</body>
</html>

 


5. setInterval

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>setInterval</title>
</head>
<body>
    <h2>setInterval</h2>
    <script>
        const hello = function(){
            console.log('안녕하세요. JavaScript')
        }

        const si = setInterval(hello, 3000);

        const clearInter = function(){
            clearInterval(si);
            console.log('hello()가 중지되었습니다')
        }
    </script>
    <p><button onclick="clearInter()">중지</button></p>
</body>
</html>

6. 시계 만들기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>시계만들기</title>
</head>
<body> 
    <h2>시계만들기</h2>
    <script>
        function makeClock(){
            const date = new Date();
            yy = date.getFullYear();
            MM = date.getMonth() + 1;
            dd = date.getDate();
            hh = date.getHours();
            mm = date.getMinutes();
            ss = date.getSeconds();
            console.log(`${yy}-${MM}-${dd} ${hh}:${mm}:${ss}`);
        }

        let si;

        function startClock(){
            si =setInterval(makeClock, 1000);
        }

        function stopClock(){
            clearInterval(si);
            console.log('종료!');
        }
    </script>
    <button onclick="startClock()">시작</button>
    <button onclick="stopClock()">중지</button>
    
</body>
</html>

7. location 객체

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>location객체</title>
</head>
<body> 
    <h2>location 객체</h2>
    <script>
        function pageInfo(){
            console.log(`현재 문서의 URL주소: ${location.hredf}`);
            console.log(`현재 문서의 protocol: ${location.protocol}`);
            console.log(`현재 문서의 hostname: ${location.hostname}`);
            console.log(`현재 문서의 pathname: ${location.pathname}`);
        }

        function sendit(){
            location.href = 'https://python.org'
        }

    </script>
    <p>
    <button onclick="pageInfo()">페이지 정보</button>
    <button onclick="sendit()">이동하기</button>
    <button onclick="location.reload()">새로고침</button>
    </p>
</body>
</html>

8. history 객체

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>history객체</title>
</head>
<body> 
    <h2>history 객체</h2>
    <button onclick="history.back()">뒤로</button>
    <button onclick="history.forward()">앞으로</button>
    <button onclick="history.go(0)">새로고침</button>

</body>
</html>

9. navigator 객체

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>navigator객체</title>
</head>
<body> 
    <h2>navigator 객체</h2>
    <script>
        const success = function(loc){
            console.log(loc.coords.latitude);
            console.log(loc.coords.longitude);
        }
        const fail = function(msg){
            console.log(msg.code);
        }

        navigator.geolocation.getCurrentPosition(success,fail)
    </script>

</body>
</html>

10. 문서 객체 모델1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체모델1</title>
</head>
<body> 
    <h2>문서 객체 모델1 </h2>
    <ul>
        <li name="markup">HTML</li>
        <li>CSS</li>
        <li id="javascript" class="js">JavaScript</li>
        <li class="js">React</li>
        <li class="backend">Apache</li>
        <li class="backend">NgineX</li>
        <li id="nodejs" class="js">Node.js</li>
        <li id="vue" class="js">Vue</li>
    </ul>
    <script>
        const tagName = document.getElementsByTagName('li');
        for(let i = 0; i < tagName.length; i++){
            console.log(tagName[i]);
            tagName[i].style.color = 'gold';
        }

        console.log('-----------');

        const className = document.getElementsByClassName('js');
        for(let i = 0; i < className.length; i++){
            console.log(className[i]);
            className[i].style.color = 'deeppink';
        }

        console.log('-----------');

        const id = document.getElementById('javascript');
        console.log(id);
        id.style.color = 'greenyellow';

        console.log('-----------');

        const name = document.getElementsByName('markup');
        for(let i = 0; i < name.length; i++){
            console.log(name[i]);
            name[i].style.color = 'blue';
        }

        console.log('-----------');
        
        const qsa = document.querySelectorAll('li.backend')
        for(let i = 0; i < qsa.length; i++){
            console.log(qsa[i]);
            qsa[i].style.color = 'navy';
        }
    </script>
</body>
</html>

11. 문서 객체 모델2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체모델2</title>
    <script>
        window.onload = function(){
            const gnb = document.getElementById('gnb')
            console.log(gnb)

            console.log(gnb.parentNode);
            console.log(gnb.children[0]);
            console.log(gnb.children[1]);

            console.log(gnb.children[0].children[0]);
            console.log(gnb.children[0].children[1]);
            console.log(gnb.children[0].children[0].nextElementSibling);
            console.log(gnb.children[0].firstChild);
            console.log(gnb.children[0].firstElementChild);
        }
    </script>
</head>
<body> 
    <h2>문서 객체 모델2</h2>
    <div>
        <nav id="gnb">
            <ul>
                <li>내용 1</li>
                <li>내용 2</li>
                <li>내용 3</li>
            </ul>
        </nav>
    </div>
</body>
</html>

12. 노드메서드

노드 생성 / 속성노드 생성 / 텍스트노드생성 - 기능 구현
속성노드 삭제 시 react 적힌 부분이 바뀜

 

노드 복제 버튼 선택시

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>노드메서드</title>
</head>
<body>
    <h2>노드메서드</h2>
    <script>
        function appendNode(){
            const parent = document.getElementById('list');
            console.log(parent);
            const newItem = document.getElementById('item1');
            console.log(newItem);
            // appendChild():
            parent.appendChild(newItem);
        }

        function insertNode(){
            const parent = document.getElementById('list');
            const backend = document.getElementById('backend');
            const newItem = document.getElementById('item2');
            // insertBefore(): 새로운 노드를 특정 자식 노드 바로 앞에 추가
            parent.insertBefore(newItem, backend);
        }

        function appendText(){
            const text = document.getElementById('text').firstChild;
            console.log(text);
            // 새로운 노드를 텍스트 데이터로 추가
            text.insertData(7, '아주 피곤한 수요일');
        }

        function createNode(){
            const newItem = document.getElementById('item1');
            // createElement(): 새로운 요소 노드를 만듦
            const newNode = document.createElement('p'); // <p></p>

            // <p><strong>🤩새로운 요소가 추가됨</strong></p>
            // innerHtml: HTML요소와 텍스트를 삽입
            // innerText: 텍스트만 삽입
            newNode.innerHTML = '<strong>🤩 새로운 요소가 추가됨</strong>';
            document.body.insertBefore(newNode, newItem);

        }

        function createAttr(){
            const newItem = document.getElementById('item2');
            // createAttribute(): 새로운 속성 노드를 만듦
            const newAttr = document.createAttribute('style');  //style=''

            //style='color:deeppink; background-colur:gold;';
            newAttr.value = 'color:deeppink; background-color:gold;';

            newItem.setAttributeNode(newAttr);
        }

        function createText(){
            const textNode = document.getElementById('ct');
            const newText = document.createTextNode('🤩😀😎🍟')
            textNode.appendChild(newText);
        }

        function removeNode(){
            const parent = document.getElementById('list');
            const removeItem = document.getElementById('backend');
            // removeChild(): 자식 노드 리스트에서 특정 자식 노드를 제거. 노드가 제거되면 해당 노드를 반환. 노드가 제거될 때 노드의 자식들도 다같이 제거
            const result = parent.removeChild(removeItem);
            console.log(result);
        }

        function removeAttr(){
            const newItem = document.getElementById('item2');
            // removeAttribute(): 특정 속성 노드를 제거
            newItem.removeAttribute('style');
        }

        function cloneElement(){
            const parent = document.getElementById('list');
            const originItem = document.getElementById('cl');
            // cloneNode(): 기존의 존재하는 노드와 동일한 새로운 노드를 생성하여 반환(true)자식까지 복사, false 자식은 복사하지 않음
            parent.appendChild(originItem.cloneNode(true));
        }
    </script>

    <h2 id="cl">노드</h2>
    <div id="list">
        <p id="backend">node.js</p>
        <p>HTML</p>
        <p>CSS</p>
    </div>
    <p id="item2">React</p>
    <p id="item1">JavaScript</p>
    <hr>
    <p id="text">현재 시간은 오후 3시</p>
    <button onclick="appendNode()">노드추가1</button>
    <button onclick="insertNode()">노드추가2</button> 
    <button onclick="appendText()">텍스트노드추가</button> 
    <hr>
    <p id="ct"></p>
    <hr>
    <button onclick="createNode()">노드생성</button>
    <button onclick="createAttr()">속성노드생성</button>
    <button onclick="createText()">텍스트노드생성</button>
    <hr>
    <button onclick="removeNode()">노드삭제</button>
    <button onclick="removeAttr()">속성노드삭제</button>
    <hr>
    <button onclick="cloneElement()">노드복제</button>

</body>
</html>