블록체인 sw개발자

[JS] 요소(Element)찾기

sang969 2023. 7. 9. 21:58

Javascript에서 DOM의 특성 요소(Element)를 찾는 방법이 있다.

 

  • getElementById()
  • getElementsByClassName()
  • getElementByTagName()
  • querySelector()
  • querySlectorAll()

 

getElementById()

 

자바스크립트 getElementById() 메소드는 특정 id 속성을 가진 요소를 검색하고 그 요소를 리턴합니다. 이는 HTML DOM

관련 스크립트를 짤 때 가장 유용하고 일반적으로 쓰이는 메소드입니다. 주로 document의 일부 요소를 칮거니 조작할 때 많이 사용합니다.

이 메소드는 특정 iddocument를 검색하는데 요소를 찾지 못한 경우 null을 리턴합니다. id는 원래 페이지 내에숴 고유한 값 이어야 하기 때문에 여러 요소가 같은 id로 지정된 경우 getElementById() 메소드는 첫 번째로 찾아낸 요소만을 리턴합니다.

 Ex)

html
여기서 버튼을 누르면 다음과 같이 문장이 변경됩니다:

위의 HTML 코드의 <body> 요소의 첫 번째 요소로 <p>를 넣었고 이 요소의 id를 “demo1″로 지정했습니다. 그 다음 <button> 요소를 넣어 클릭하면 myFunction1() 함수를 호출하게 작성했습니다.

 

Ex 2)

이번에는 기존 요소의 내용을 가져와 document에 그대로 추가하는 예제

<!DOCTYPE html>
<html>

<body>
  <p id="element1">GetElementById1</p>
  <hr>
  <p>document에 요소 내용 복사</p>
  <script>
    const s1 = document.getElementById("element1").innerHTML;
    document.write(s1);
  </script>
  <hr>
</body>

</html>

 

 


getElementsByClassName()

 

이 함수는 태그의 class = "" 속성을 사용하여 접근한다.
동일한 class명이 존재할수 있기 때문에 (id속성은 html 문서에 동일한 id속성이 존재하면 안된다.)
id 속성을 사용하여 접근하는 getElementById() 와 달리getElementByClassName() 은 컬레션 객체를 반환한다.
따라서 for문을 사용하거나 특정 index에 위치한 element를 반환받아 사용할수있다.

 

Ex)
<ul>
  <li class = "superman hero">Superman</li> 
  <li class = "batman hero">Batban</li>
  <li class = "pororo hero">pororo</li>
</ul>

li에 태그에 hero라는 클래스를 부여하였습니다.

const hero = document.getElementsByClassName("hero");
  
for(let i = 0; i<hero.length; i++){
  hero[i].style.fontSize = "xx-large"; 
}

결과

 


getElementByTagName()

 

메서드명 그 의미를 그대로 가지고 있어, 특정 tag명을 가지고 있는 dom 요소에 접근하기 위한 메서드이다.

name : 찾으려는 태그 요소명을 의미한다. (특수 문자 * 은 모든 엘리먼트를 나타낸다.)

 

ex)

<!doctype html>
<html lang="ko">
  <head>
    <script src="./test.js"></script>
    <title>mineItRecord</title>
  </head>
  <body>
    <div>div-1</div>
    <div>div_2</div>
    <div>
      <span>span</span>
      <p>p</p>
    </div>
    <div id="wrap" class="wrap">
      <span class="sp">span</span>
    </div>
  </body>
</html>
// 기본 사용법
document.getElementsByTagName('div');
// HTMLCollection(4) [div, div, div, div#wrap.wrap, wrap: div#wrap.wrap]
document.getElementsByTagName('span');
// HTMLCollection(2) [span, span.sp]

// 모든 태그 요소 가져오기
document.getElementsByTagName('*');
// HTMLCollection(13) 
// [html, head, script, title, body, div, div, div, span, p, div#wrap.wrap, span.sp, script, wrap: div#wrap.wrap]

// 특정 요소 내부에서 스캔하기
wrap.getElementsByTagName('span'); // HTMLCollection [span.sp]
document.getElementsByTagName('div')[2].getElementsByTagName('p');
// HTMLCollection [p]
document.getElementsByTagName('div')[2].getElementsByTagName('*');
// HTMLCollection(2) [span, p]

getElementsByTagName() 메서드는 특이하게도 '*'을 사용할 수 있으니 알아두도록 하자.

 


querySelector(), querySelectorAll()

 

query selector()

특정 name, id, calss 를 제한하지 않고 css선택자를 사용하여 요소를 찾습니다.

같은 id 또는 class 일 경우 스크립트의 최상단 요소만 로직에 포함합니다.

querySelector(#id) => id 값 id를 가진 요소를 찾습니다.
querySelector(.class) => class 값 class를 가진 요소를 찾습니다

 

Ex)

class="example"로 첫 번째 <p> 요소를 가져옵니다.

<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html>
<body>

<h1>The Document Object</h1>
<h2>The querySelector() Method</h2>

<p>Add a background color to the first p element with class="example".</p>

<h2 class="example">A heading</h2>
<p class="example">A paragraph.</p> 

<script>
document.querySelector("p.example").style.backgroundColor = "red";
</script>

</body>
</html>

결과

 

Ex2)

id="demo"로 요소의 텍스트를 변경합니다.

<!DOCTYPE html>
<html>
<body>
<p id="demo">This is a p element with id="demo".</p>

<script>
document.querySelector("#demo").innerHTML = "Hello World!";
</script>

</body>
</html>

<!-- Hellow World! -->

Ex3)

<!DOCTYPE html>
<html>
<head>
<style>
div {
  border: 1px solid black;
  margin-bottom: 10px;
}
</style>
</head>
<body>
<div>
  <h3>H3 element</h3>
  <p>I am a p element, my parent is a div element.</p>
</div>
<div>
  <h3>H3 element</h3>
  <p>I am a p element, my parent is also a div element.</p>
</div>

<p>Click the button to change the background color of the first p element in the document where the parent is a div element.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  var x = document.querySelector("div > p");
  x.style.backgroundColor = "red";
}
</script>
</body>
</html>

 

Try it 박스 클릭시 I am a p element, my parent is a div element. 에 붉은 선이 생긴

 


querySelectorAll()

querySelector와 사용 방법은 동일하며 선택자를 선택하여 배열과 비슷한 객체인 nodeList를 반환합니다. 반환객체가 nodeList이기에 for문 또는 forEach문을 사용합니다.

아래 코드와 같이 ","를 사용하면 여러 요소를 한번에 가져올 수 있습니다.

querySelectorAll("#id,.class")

ex)

첫 번째 <p> 요소에 배경색을 추가합니다.

<!DOCTYPE html>
<html>
<body>
<h1>The Document Object</h1>
<h2>The querySelectorAll() Method</h2>

<p>Add a background color to the first p element:</p>
<p>This is a p element.</p>
<p>This is a p element.</p>

<script>
const nodeList = document.querySelectorAll("p");
nodeList[0].style.backgroundColor = "red";
</script>

</body>
</html>

 

Ex2)

class="example"로 첫 번째 <p> 요소에 배경색을 추가합니다.

<!DOCTYPE html>
<html>
<body>
<h1>The Document Object</h1>
<h2>The querySelectorAll() Method</h2>

<p>Add a background color to the first p element with class="example":</p>

<h2 class="example">A heading</h2>
<p class="example">A paragraph.</p> 
<p class="example">A paragraph.</p> 

<script>
const nodeList = document.querySelectorAll("p.example");
nodeList[0].style.backgroundColor = "red";
</script>

</body>
</html>

Ex3)

<!DOCTYPE html>
<html>
<body>

<h1>A H1 element</h1>
<h2>A H2 element</h2>
<h3>A H2 element</h3>
<div>A DIV element</div>
<p>A p element.</p>
<p>A p element with a <span style="color:brown;">span</span> element inside.</p>

<script>
const nodeList = document.querySelectorAll("h3, div, span");
for (let i = 0; i < nodeList.length; i++) {
  nodeList[i].style.backgroundColor = "red";
}
</script>

</body>
</html>