body 안에 모든 id를 찾고 싶습니다.

body 안에 모든 id를 찾고 싶습니다.

QA

body 안에 모든 id를 찾고 싶습니다.

답변 3

본문

질문 그대로 입니다.

body 안에 있는 id를 찾고 싶습니다.

특정 아이디가 아닌 10개가 있으면 그 전체를 찾고 싶고 그 해당하는 아이디 값도 찾고 싶습니다.

생각대로 잘 작동이 안되네요...

#id

이 질문에 댓글 쓰기 :

답변 3

해당 파일안에



<script>
    document.addEventListener("DOMContentLoaded", function() {
        // 모든 id 속성을 가진 요소들을 가져옵니다.
        const elements = document.querySelectorAll('body [id]');
        const ids = [];

        // 각 요소의 id 속성을 배열에 저장합니다.
        elements.forEach(element => {
            ids.push(element.id);
        });

        // 결과를 콘솔에 출력합니다.
        console.log(ids);
    });
</script>

요소보기로 콘솔 확인해보세요.

 

3554430148_1718350094.7332.png

원하시는 내용이 맞는지 참고를 해보시겠어요?

 

 

 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>ID찾기</title>
</head>
<body>
    <div id="example1">Example 1</div>
    <div id="example2">Example 2</div>
    <p id="example3">Example 3</p>
    <span id="example4">Example 4</span>
    <!-- 여러 요소들... -->
    
    <script>
        // 모든 id를 찾는 함수
        function findAllIdsInBody() {
            // body 내의 모든 요소를 가져옴
            const elements = document.body.getElementsByTagName("*");
            // id를 저장할 배열
            const ids = [];

            // 각 요소를 순회하며 id를 배열에 추가
            for (let i = 0; i < elements.length; i++) {
                const id = elements[i].id;
                if (id) {
                    ids.push(id);
                }
            }

            return ids;
        }

        // 함수 호출 및 결과 출력
        const allIds = findAllIdsInBody();
        console.log("All IDs in body:", allIds);  //개발자모드 콘솔창에 보임
    </script>
</body>
</html>

 

 

 

 

답변을 작성하시기 전에 로그인 해주세요.
QA 내용 검색
질문등록
전체 0
© SIRSOFT
현재 페이지 제일 처음으로