요소 가져오기

클래스 이름으로 가져오기 .getElementsByClassName("클래스 네임")
아이디 이름으로 가져오기 .getElementById ("아이디 이름")
태그 하나 가져오기 .querySelector("#id") or (태그)
태그 여러개 가져오 .querySelectorAll ( 태그 여러개 )

 


1. 클래스 이름을 이용한 선택

<!-- 
    DOM(Document Object Model)

    HTML 태그들을 하나씩 객체화한 것.
    HTML 페이지의 내용과 모양을 제어하기 위해서 사용되는 객체이다.
    HTML 태그 당 DOM 객체가 하나씩 생성된다.
    HTML 태그의 포함관계에 따라서 부모, 자식, 형제자매 관계로 구성된다.
 -->
<!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>
        <h1>클래스 이름을 이용한 선택</h1>
        <ul>
            <li class="odd item">첫 번째 아이템이에요!</li>
            <li class="even item">두 번째 아이템이에요!</li>
            <li class="odd item">세 번째 아이템이에요!</li>
            <li class="even item">네 번째 아이템이에요!</li>
            <li class="odd item">다섯 번째 아이템이에요!</li>
        </ul>
    </body>
    <script>
        HTMLCollection.prototype.forEach = Array.prototype.forEach;

        // odd 글자색을 빨간색으로 변경
        document.getElementsByClassName("odd").forEach((li) => {
            li.style.color = "red";
        });

        // even은 글자색을 녹색으로 변경

        document.getElementsByClassName("even").forEach((li) => {
            li.style.color = "green";
        });

        // 위 코드를 한 줄로 작성

        document.getElementsByClassName("item").forEach((li) => {
            li.className.includes("odd")
                ? (li.style.color = "red")
                : (li.style.color = "green");
        });

        document.getElementsByClassName("item").forEach((li) => {
            li.style.color = li.className.includes("odd") ? "red" : "green";
        });
    </script>
</html>

<!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>
        <ul>
            <li class="car ferrari">페라리</li>
            <li class="car">람보르기니</li>
            <li class="car">벤츠</li>
        </ul>
    </body>
    <script>
        // 자동차 중 ferrari만 빨간색 글자로 설정,
        // 나머지 자동차는 글자 크기를 20xp로 설정(DOM객체.style.fontSize)

        HTMLCollection.prototype.forEach = Array.prototype.forEach;

        document.getElementsByClassName;

        document.getElementsByClassName("car").forEach((car) => {
            if (car.className.includes("ferrari")) {
                car.style.color = "red";
                return;
            }
            car.style.fontSize = "20px";
        });

        // 자동차 중 ferrari만 빨간색 글자로 설정,
        // 나머지 자동차는 글자 크기를 20xp로 설정(DOM객체.style.fontSize)
    </script>
</html>
<!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>
        <ul>
            <li class="car ferrari">페라리</li>
            <li class="car">람보르기니</li>
            <li class="car">벤츠</li>
        </ul>
    </body>
    <script>
        // 자동차 중 ferrari만 빨간색 글자로 설정,
        // 나머지 자동차는 글자 크기를 20xp로 설정(DOM객체.style.fontSize)

        HTMLCollection.prototype.forEach = Array.prototype.forEach;

        document.getElementsByClassName;

        document.getElementsByClassName("car").forEach((car) => {
            if (car.className.includes("ferrari")) {
                car.style.color = "red";
                return;
            }
            car.style.fontSize = "20px";
        });

        // 자동차 중 ferrari만 빨간색 글자로 설정,
        // 나머지 자동차는 글자 크기를 20xp로 설정(DOM객체.style.fontSize)
    </script>
</html>

 

 

 


2. name 속성 선택

 

  • name에 특수기호 '-'가 들어가면 [ ] 대괄호로 불러준다.
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>name 속성 선택</title>
    </head>
    <body>
        <form action="" name="join">
            <div>
                <input type="text" name="user-id" placeholder="아이디" />
            </div>
            <div>
                <input
                    type="password"
                    name="user-password"
                    placeholder="비밀번호"
                />
            </div>
            <div>
                <label> </label>
            </div>
        </form>
    </body>
    <script>
        // const [id] = document.getElementsByName("user-id");
        // const [password] = document.getElementsByName("user-password");
        if (!document.join["user-id"].value) {
            console.log("아이디 작성");
            // return;
        }

        console.log(document.join["user-id"]);

        // // 비밀번호 검사하기
        if (!document.join["user-password"].value) {
            console.log("비밀번호 작성");
        }
    </script>
</html>

 

3. 유효성 검사

 

  • 아이디에 값이 없을때 "아이디"를 콘솔에 출력
  • 비밀번호에 값이 없을 때 "패스워드" 출력
  • 아이디 저장을 처음부터 체크되도록 설정
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>name 속성 선택 실습</title>
    </head>
    <body>
        <form action="" name="login">
            <input type="text" name="email" />
            <input type="password" name="password" />
            <div>
                <label>
                    <input type="checkbox" name="save-id" value="" /> 아이디
                    저장
                </label>
            </div>
        </form>
    </body>
    <script>
        // 이메일과 비밀번호를 유효성 검사진행
        if (!document.login.email.value) {
            console.log("아이디");
        }
        if (!document.login.password.value) {
            console.log("패스워드");
        }

        // 아이디 저장을 처음부터 체크되도록 설정

        document.login["save-id"].checked = true;
    </script>
</html>

 


4. innerText / innerHTML

 

<!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>
        <h1>아이디 속성 선택</h1>
        <div id="first">
            <strong> 첫 번째 DIV 입니다. </strong>
        </div>
        <div id="second">두 번째 DIV 입니다.</div>
        <textarea id="third">세 번째 DIV 입니다.</textarea>
        <button id="btn">완료</button>
    </body>
    <script>
        const first = document.getElementById("first");
        const second = document.getElementById("second");
        console.log(first.innerHTML);
        console.log(first.innerText);

        second.innerHTML = `<strong>${second.innerText}</strong>`;
        second.innerText = `<strong>${second.innerText}</strong>`;

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

        // value: 사용자가 새롭게 입력한 값을 포함해서 가져오기
        console.log(third.value);

        // innerHTML: 기존에 작성되었던 내용만 가져오기
        console.log(third.innerHTML);
    </script>
</html>


 

5. CSS 선택자로 선택

 

  • 두 코드의 결과는 같음
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>CSS 선택자로 선택</title>
    </head>
    <body>
        <h1>CSS 선택자로 선택</h1>
        <p>갖고 싶은 위시 리스트</p>
        <ul>
            <li>집</li>
            <li>맥북</li>
            <li>땅</li>
            <li>건물</li>
            <li>아이폰14</li>
            <li>아이폰12</li>
        </ul>
    </body>
    <script>
        // 내용에 아이폰이 들어간 태그의 스타일 중,
        // fontSize를 30px, color: pink로 변경
        const items = document.querySelectorAll("ul li");
        console.log(items);

        items.forEach((item) => {
            if (item.innerText.includes("아이폰")) {
                with (item.style) {
                    fontSize = "30px";
                    color = "pink";
                }
            }
        });   
        
        </script>
</html>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>CSS 선택자로 선택</title>
    </head>
    <body>
        <h1>CSS 선택자로 선택</h1>
        <p>갖고 싶은 위시 리스트</p>
        <ul>
            <li>집</li>
            <li>맥북</li>
            <li>땅</li>
            <li>건물</li>
            <li>아이폰14</li>
            <li>아이폰12</li>
        </ul>
    </body>
    <script>
        // 내용에 아이폰이 들어간 태그의 스타일 중,
        // fontSize를 30px, color: pink로 변경
 
        const items = document.querySelectorAll("ul li");
        console.log(items);

        items.forEach((item) => {
            if (item.innerText.includes("아이폰")) {
                item.style.fontSize = "30px";
                item.style.color = "pink";
            }
        });

        items.forEach((item) => {
            if (item.innerText.includes("아이폰")) {
                with (item.style) {
                    fontSize = "30px";
                    color = "pink";
                }
            }
        });
        // 내용에 아이폰이 들어간 태그의 스타일 중,
        // fontSize를 30px, color: pink로 변경
    </script>
</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>
        <p>DOM 트리에 동적으로 객체를 삽입할 수 있다.</p>
        <p>
            createElement("태그명"), appendChild("태그객체"),
            removeChild("태그객체")
        </p>
        <p>위 3개의 메소드를 이용해서 새로운 객체를 생성, 삽입, 삭제한다.</p>
        <a id="create" href="">DIV 생성</a>
    </body>
    <script>
        const a = document.querySelector("#create");
        // 색은 규칙성이 없으므로 리스트에 담음
        const colors = new Array(
            "yellow",
            "red",
            "blue",
            "green",
            "skyblue",
            "orange",
            "pink"
        );

        globalThis.number = 0;
        a.onclick = (e) => {
            // a태그의 디폴트 이벤트를 막음 (이동을 막음)
            e.preventDefault();
            const i = Math.floor(Math.random() * colors.length);
            // 새롭게 생성한 div개체 (비어있는 div)
            const newDiv = document.createElement("div");

            //++을 앞에 쓰면1부터 뒤에쓰면 0부터
            newDiv.innerText = `새로 생성된 div${++number} 태그`;
            newDiv.style.backgroundColor = colors[i];
            newDiv.onclick = (e) => {
                // e.target: 이벤트 객체를 통해 이벤트를 발생시킨 객체를 가져올 수 있다.
                // 부모를 찾아가서 아이를 지움
                e.target.parentElement.removeChild(e.target);
            };

            // 바디에 newDiv생성
            document.body.appendChild(newDiv);
        };
    </script>
</html>

 

div를 클릭하면 삭제

 

 

'컴퓨터 비전 > Javascript' 카테고리의 다른 글

자바스크립트 date  (0) 2024.02.07
fetch  (0) 2024.01.30
object, spread, rest , 비구조화 할당  (0) 2024.01.29
callback  (0) 2024.01.29
function  (0) 2024.01.29