className()와 classList(), setAttribute(), getAttribute()

서지우·2023년 7월 18일
0

JavaScript

목록 보기
6/11

className

className은 특정 엘리먼트의 클래스 속성의 값을 가져오거나 설정할 수 있다.

var cName = element.className;
element.className = cName;

classList

classList는 읽기 전용 프로퍼티이다.
공백으로 구분된 문자열인 element.className을 통해 엘리먼트의 클래스 목록에 접근하는 방식을 대체하는 간편한 방법이다.

메소드

1. add

classList.add( String [, String [, ...]] )

지정한 클래스 값을 추가한다.
만약 추가하려는 클래스가 엘리먼트의 class 속성에 이미 존재한다면 무시한다.

2. remove

classList.remove( String [, String [, ...]] )

지정한 클래스 값을 제거한다.

존재하지 않는 클래스를 제거하는 것은 에러를 발생하지 않는다.


3. item(Number)

콜렉션의 인덱스를 이용하여 클래스 값을 반환한다.

4. toggle

classList.toggle( String [, force] )

하나의 인수만 있을 때 클래스 값을 토글링한다.
즉, 클래스가 존재한다면 제거하고 false를 반환하며, 존재하지 않으면 클래스를 추가하고 true를 반환한다.

두번째 인수가 있을 때 두번째 인수가 true로 평가되면 지정한 클래스 값을 추가하고 false로 평가되면 제거한다.

5. contains

classList.contains( String )

지정한 클래스 값이 엘리먼트의 class 속성에 존재하는지 확인한다.

6. replace

classList.replace( oldClass, newClass )

존재하는 클래스를 새로운 클래스로 교체한다.


setAttribute()

.setAttribute()는 선택한 요소의 속성 값을 정한다.

element.setAttribute( 'attributename', 'attributevalue' )

getAttribute()

getAttribute()는 선택한 요소의 특정 속성의 값을 가져온다.

element.getAttribute( 'attributename' )

실습 - s13.html

주석으로 설명..

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 태그도 객체다 -->
    <h1 id="first">첫번째</h1>

    <script>
        
        const firstTag = document.querySelector("#first");
        // 태그의 속성을 객체의 프로퍼티처럼 가져올 수 있다
        console.log(firstTag.id);
        firstTag.id = "next";
        // 태그에 없었던 속성도 만들어서 넣어 줄 수 있다
        // className은 class 내용 전체
        // classList는 class 내용을 띄어쓰기 기준으로 리스트
        firstTag.className = "my-h1";
        // firstTag.className = "my-h1 red";
        firstTag.classList.add("blue");

        // 태그가 가지고 있는 메소드를 정의할 수 있다
        firstTag.onclick = function(){
            alert("클릭");
        }

        // 기존 태그에 없던 변수도 만들 수 있다
        firstTag.asdf = "새로운 변수";

        // 기존 태그에 없던 함수도 만들 수 있다.
        firstTag.hello = () => {
            alert("안녕하세요");
        };

        // firstTag.adsf = "새로운 변수";는 작동이 안되는 브라우저가 있을 수 있다
        // 기존 태그에 없던 변수나 함수는 위의 방식보다 아래 방식으로 하는게 낫다
        firstTag.setAttribute("asdf", "새로운 변수");
        console.log(firstTag.getAttribute("asdf"));
        // setAttribute는 key문자열/ value문자열이기 때문에 아래 코드는 작동이 안된다
        // firstTag.setAttribute("hello", () => {
        //     alert("안녕하세요");
        // });

        // firstTag.getAnimations("hello")(); //에러

        // console.log(firstTag.asdf);
        // firstTag.hello();

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

실행결과


실습 - s15.html

주석으로 설명

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .red{
            color: red;
        }
    </style>
    <title>Document</title>
</head>
<body>
    <h1 id = "first">내용</h1>
    <script>
        // 스타일 변경
        const firstTag = document.querySelector("#first");
        // firstTag.style.color = "red";
        // 이렇게 사용하는 것은 추천하지 않는다.
        // css를 id나 class 등으로 컨트롤 할 수 없을 경우에만 사용
        // firstTag.stylee.color = "red";

        // 클래스를 추가 및 삭제해서  스타일 변경
        // firstTag.classList.add("red");

        // firstTag.classList 클릭할 때 반응
        firstTag.onclick = () => {
            // firstTag 클래스 중 red가 포함되어 있으면?
            if(firstTag.classList.contains("red")){
                // red를 클래스에서 제거
                firstTag.classList.remove("red");
            }else{
                // red를 클래스에 추가
                firstTag.classList.add("red");
            }
        }
    </script>
</body>
</html>

실행결과

profile
미래가 기대되는 풀스택개발자 공부 이야기~~

2개의 댓글

comment-user-thumbnail
2023년 7월 18일

정말 잘 읽었습니다, 고맙습니다!

답글 달기
comment-user-thumbnail
2023년 7월 18일

유익한 글 잘 봤습니다, 감사합니다.

답글 달기