Computer >> 컴퓨터 >  >> 프로그래밍 >> HTML

HTML DOM scripts 컬렉션 – 문법, 속성, 메서드와 예제 총정리

HTML DOM의 scripts 컬렉션은 HTML 문서 안에 포함된 모든 <script> 요소를 하나의 컬렉션으로 반환합니다. 이 컬렉션을 활용하면 문서 내 스크립트 태그의 개수를 확인하거나, 특정 인덱스 또는 id에 해당하는 스크립트 요소에 접근할 수 있습니다.

문법(Syntax)

scripts 컬렉션의 기본 문법은 다음과 같습니다.

document.scripts

scripts 객체의 속성(Property)

속성설명
lengthHTML 문서 내 컬렉션에 포함된 <script> 요소의 개수를 반환합니다.

scripts 객체의 메서드(Method)

메서드설명
[index]컬렉션에서 지정한 인덱스 위치의 <script> 요소를 반환합니다.
item(index)컬렉션에서 지정한 인덱스 위치의 <script> 요소를 반환합니다.
namedItem(id)컬렉션에서 지정한 id 값을 가진 <script> 요소를 반환합니다.

예제(Example)

다음은 scripts 컬렉션을 활용한 실제 예제입니다. 버튼을 클릭하면 현재 페이지에 존재하는 <script> 요소의 개수가 화면에 표시됩니다.

<!DOCTYPE html>
<html>
<head>
<style>
    html{
       height:100%;
    }
    body{
       text-align:center;
       color:#fff;
       background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
       height:100%;
    }
    p{
       font-weight:700;
       font-size:1.2rem;
    }
    ul{
       list-style-type: none;
       padding:0;
    }
    .btn{
       background:#0197F6;
       border:none;
       height:2rem;
       border-radius:2px;
       width:50%;
       margin:2rem auto;
       display:block;
       color:#fff;
       outline:none;
       cursor:pointer;
    }
    .show{
       font-size:1.5rem;
       font-weight:bold;
    }
</style>
</head>
<body>
<script>
console.log("script one");
</script>
<h1>DOM scripts Collection Demo</h1>
<p>안녕하세요! 이 페이지에는 두 개의 script 요소가 있습니다:</p>
<script>
console.log("script two");
</script>
<button onclick="show()" class="btn">Show No. Of Script</button>
<div class='show'></div>
<script>
    function show() {
       var scriptList = document.scripts;
       document.querySelector(".show").innerHTML=scriptList.length;
    }
</script>
</body>
</html>

실행 결과(Output)

위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

HTML DOM scripts 컬렉션 – 문법, 속성, 메서드와 예제 총정리

화면의 “Show No. of Script” 버튼을 클릭하면, 해당 페이지에 포함된 <script> 요소의 총 개수가 표시됩니다.

HTML DOM scripts 컬렉션 – 문법, 속성, 메서드와 예제 총정리