투케이2K

574. (javaScript) [간단 소스] 자바스크립트 document.querySelectorAll 사용해 특정 클래스 내에 포함 된 div 내용 검색 수행 본문

JavaScript

574. (javaScript) [간단 소스] 자바스크립트 document.querySelectorAll 사용해 특정 클래스 내에 포함 된 div 내용 검색 수행

투케이2K 2026. 7. 15. 18:45
728x90
반응형

[개발 환경 설정]

개발 툴 : Edit++ / Vscode

개발 언어 : JavaScript

 

[소스 코드]

-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------

- 개발 환경 : Web


- 개발 기술 : JavaScript / document.querySelectorAll / getAttribute


- 사전) 👉 document.querySelectorAll 간략 설명 :

  >> document.querySelectorAll()은 CSS 선택자(CSS Selector)를 사용하여 DOM 요소를 여러 개 선택하는 JavaScript 메서드입니다.

    - selector : CSS 선택자 문자열
    - 반환값 : NodeList 객체 (선택된 요소들의 목록)

  >> document.querySelectorAll() 간단 사용 방법 : 

    - 클래스 선택 : 
    
        <div class="item">A</div>
        <div class="item">B</div>
        <div class="item">C</div>

        const items = document.querySelectorAll(".item");

    - 태그 선택 : 

        const divs = document.querySelectorAll("div"); // 모든 <div> 요소를 가져옵니다.

    - ID 선택 : 

        const element = document.querySelectorAll("#content"); // ID는 원래 하나만 존재해야 하지만, 반환 타입은 여전히 NodeList입니다.

    - 복합 선택자 사용 : 

        const links = document.querySelectorAll("nav ul li a"); // CSS에서 사용하는 선택자를 그대로 사용할 수 있습니다.

    - 여러 조건 선택 : 

        const elements = document.querySelectorAll(".btn, .link"); // 쉼표(,) 사용

    - 속성(Attribute) 선택 : 

        <input type="text">

        const inputs = document.querySelectorAll('input[type="text"]');
  
-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[소스 코드]
-----------------------------------------------------------------------------------------

<!DOCTYPE HTML>
<html lang="ko" translate="no">
<head>
    <title>javaScriptTest</title>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <!-- [반응형 구조 만들기] -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

    <!-- [Chrome / Edge (Chromium)에서 자동 번역 기능을 완전히 비활성화] -->
    <meta name="google" content="notranslate">

    

    <!-- 내부 CSS 스타일 지정 -->
    <style>

        html, body {
            width: 100%;
            height: 100%;
            margin : 0 auto;
            padding : 0;
            border : none;
            background-color: #666;
        }

    </style>





    <!-- ✅ [스크립트 : CDN 주소 설정] --> 
    <!-- <script src="https://code.jquery.com/jquery-latest.min.js"></script> -->







    <!-- [자바스크립트 코드 지정] -->
    <script type="module">    


    // -----------------------------------------------------------------
    // ✅ [Window.onload 웹 브라우저 로드 완료]
    // -----------------------------------------------------------------
    window.onload = function() {
        console.log("[window onload] : [html 최초 로드 및 이벤트 상시 대기 실시] : [start]");

        try {

            // ------------------------------------------------
            // 🟦 특정 div 클래스 내에 단어가 포함 되었는지 확인 메소드 생성
            // ------------------------------------------------             
            let searchCard = function(keyword){
                try {

                    if (keyword === null || keyword === undefined || keyword === ''){
                        console.error('searchCard : error : input data is null');
                        return;
                    }
                    
                    // document.querySelectorAll 를 사용해 div 내용을 검색하려는 클래스 영역 지정
                    const cards = document.querySelectorAll("#certView .setting-card");

                    cards.forEach(card => {
                        let text = card.textContent.trim();

                        // 👉 필요 시 줄바꿈 제거 수행
                        text = text.replace(/[\r\n]+/g, ''); // 줄바꿈(\n, \r\n, \r)을 모두 제거
                        //text = text.replace(/[\r\n\t]+/g, ''); // 줄바꿈 + 탭 제거

                        if (text.includes(keyword)) {
                            console.log("searchCard : 단어 찾음 : ", card, ' / ', text);

                            // 👉 Attribute 속성이 설정 된 경우 특정 속성 정보도 추가 확인
                            const onclickValue = card.getAttribute("onclick"); 

                            
                            // 👉 함수 명칭과 파라미터 동적 파싱
                            //const match = onclickValue.match(/openCert\('(.+?)'\)/); // 특정 함수 명칭 지정
                            
                            const funcMatch = onclickValue.match(/^(\w+)\(/);
                            const paramsMatch = onclickValue.match(/\((.*)\)/);

                            if (funcMatch && paramsMatch) {

                                const functionName = funcMatch[1];

                                const params = paramsMatch[1]
                                    .split(',')
                                    .map(item => item.trim().replace(/^'|'$/g, ''));

                                console.log("함수명 :", functionName);

                                console.log("파라미터 :", params);


                                // 👉 함수 호출 수행                                
                                const func = window[functionName];

                                if (typeof func === "function") {
                                    func(...params);
                                }
                            }

                        }
                    });

                }
                catch (exception){
                    console.error('searchCard : exception : ', exception);
                }
            }



            // ------------------------------------------------   
            // 🟦 단어 찾기 호출 수행
            // ------------------------------------------------   
            searchCard("");
            searchCard("Role");
            searchCard("클레임");



            // ------------------------------------------------   
            // 🟦 출력 로그 예시
            // ------------------------------------------------  
            /*
            [window onload] : [html 최초 로드 및 이벤트 상시 대기 실시] : [start]
            searchCard : error : input data is null            
            searchCard : 단어 찾음 :  <div class=​"setting-card" onclick=​"openCert('PROV_CLAIM')​">​…​</div>​  /  🔐              [IoT] 정책 - 클레임 인증서에 연결 된 정책                        ➜
            함수명 : openCert
            파라미터 : ['PROV_CLAIM']
            openCert :  PROV_CLAIM
            */
            // ------------------------------------------------  
            
            
        }
        catch (exception) {
            console.error("[window onload] : [Exception] : ❌ 예외 상황 발생 : ", exception);
        }

    }; 




    // -----------------------------------------------------------------
    // ✅ [openCert 메소드 구현]
    // -----------------------------------------------------------------
    window.openCert = function (params){
        console.log('openCert : ', params);
    }
      
    </script>


</head>


<body>

    <div id="certView" class="view-container">
      <div class="panel">
        <h5>🗃️ Cert View : 인증서 관리 화면</h5>
      </div>

      
      <div class="section-title">📗 AWS 플릿 프로비저닝 위한 정책 JSON 관리</div>
      <div class="row g-3">
      
        
        <div class="col-md-3">
          <div class="setting-card" onclick="openCert('PROV_CLAIM')">
            <div class="setting-left">
              <div class="setting-icon bg-green">🔐</div>
              <div>[IoT] 정책 - 클레임 인증서에 연결 된 정책</div>
            </div>
            ➜
          </div>
        </div>



        <div class="col-md-3">
          <div class="setting-card" onclick="openCert('PROV_TEMP')">
            <div class="setting-left">
              <div class="setting-icon bg-green">🔐</div>
              <div>[IoT] 템플릿 정보 - 템플릿 Parameters 정보</div>
            </div>
            ➜
          </div>
        </div>


      </div>

    </div>

</body>

</html>

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[참고 사이트]
-----------------------------------------------------------------------------------------

▶️ 45. (javascript/자바스크립트) 쿼리 셀렉터 document querySelectorAll, querySelector 사용해 특정 태그 정보 확인 및 스타일 속성 변경

https://kkh0977.tistory.com/845

https://blog.naver.com/kkh0977/222392256313?trackingCode=blog_bloghome_searchlist


▶️ 37. (javascript/자바스크립트) document createElement 사용해 동적 div 레이아웃 생성

https://kkh0977.tistory.com/834

https://blog.naver.com/kkh0977/222390682079?trackingCode=blog_bloghome_searchlist


▶️ 47. (javascript/자바스크립트) body 클릭 이벤트 감지, 동적 div 레이아웃 생성 및 클릭 이벤트 확인 - document body onclick

https://kkh0977.tistory.com/848

https://blog.naver.com/kkh0977/222392829774?trackingCode=blog_bloghome_searchlist


▶️ 106. (javascript/자바스크립트) 특정 객체 속성 값 확인 및 설정, 삭제 - getAttribute , setAttribute , removeAttribute 

https://kkh0977.tistory.com/1083

https://blog.naver.com/kkh0977/222458900585?trackingCode=blog_bloghome_searchlist


▶️ 105. (javascript/자바스크립트) cloneNode 사용해 특정 요소 객체 복사 실시 및 id 아이디 , style 스타일 변경 실시

https://kkh0977.tistory.com/1080

https://blog.naver.com/kkh0977/222457601700?trackingCode=blog_bloghome_searchlist

-----------------------------------------------------------------------------------------
 
728x90
반응형
Comments