본문 바로가기
HTML, CSS, WEB 기술,

CSS Selector 와 함께 사용하는 Document API 정리 # textContent innerText querySelector

by Developer88 2022. 11. 3.
반응형

오늘은 CSS Selector 와 이를 활용해서 자주 사용하는 Document Elements API 에 대해서 정리 해 보도록 하겠습니다.

 

1. CSS Selector

Selector를 볼 때, element, class, id, attribute에 대해서 잘 구분해 보아야 합니다.

특정한 모듈을 사용할 때 API에 항상 친절하게 설명되어 있지는 않기에,

부족한 부분은 검색을 해야 하는데요. 이 때 정확한 명칭을 알고 있으면 좀 더 빠르게 정보를 얻을 수 있습니다.

 

Selector 타입 의미
.class .infoArea class가 infoArea
.class1.class2 .info1.info2 class attribute에 name1과 name2가 들어간 것을 찾는다.
#id #tab1 id가 tab1
element p element가 p
element.class p.info1  class가 info1이고 element가 p인것

예)
<p class="info1">My best friend is Mickey.</p>
element element div p div element안에 들어있는,
p element를 찾는다.

예)
<div>
     <h2>Hello World</h2>
     <p>마이 테스트2</p>
</div>
element>element div > p dom구조상 부모가 div element인 p element를 찾는다.

예>
<div>
    <h2>Hello World</h2>
    <p>My Test2</p>
</div>
[attribute] a[href] attribute가 href 인것

예)
<a href="https://www.google.com">google.com</a>
[attribute=value] [target=_blank] target attribute이 _blank 인것

예)<a href="https://www.google.com" target="_blank">Google.com</a><br>
::after p::after p element뒤에 어떤 것을 붙인다.

예)
p::after { 
  content: "이것을 붙인다-test this";
}
::before p::before p element 앞에 어떤 것을 붙인다.

예)
p::before { 
  content: "이것을 붙인다-test this";
}
:first-child p::first-child p element들의 첫번째 자식들을 찾는다.
:last-child p::last-child p element들의 마지막 자식을 찾는다.
:nth-child(n) p:nth-child(2) p엘리먼트의 2번째 자식들을 찾는다.

 

 

2. Document  Elements API (DOM)

2-1. querySelector

querySelector()함수와 querySelectorAll()함수는,

크롬이나 Safari, FireFox모두 오래전부터 지원을 하고 있는 함수인데요.

이 함수에 Selector를 넣어주면 이에 해당하는 요소를 query해서 결과를 줍니다.

 

 

만약 아래와 같은 코드가 있다면, myclass클래스의 element를 찾아줍니다.

만약, 찾지 못하였다면, null 값을 반환해 줍니다.

 

const el = document.querySelector(".myclass");

 

이를 이용해서, 아래와 같이 요소를 찾아서 변경할 수도 있겠네요.

 

document.querySelector("p").style.backgroundColor = "blue";

 

2-2. querySelectorAll

document.querySelectorAll은 Selector조건에 맞는 여러개의 자식 엘리먼트(Child Element)를 찾는데 사용할 수 있습니다.

이 함수는 NodeList를 return 해 주므로,

반환된 아이템들에 querySelector()함수를 다시 사용할 수도 있습니다.

예를 들어, li리스트들을 받았다면, querySelector()로 그 안의 다른 요소를 찾을수도 있겠지요.

 

 

반복문을 이용해서 다음과 같이 element의 스타일을 변경할 수도 있습니다.

 

const nodeList = document.querySelectorAll(".test");
for (let i of nodeList) {
	i.style.backgroundColor = "blue";
}

 

 

2-2. innerHTML, innerText, textContent

이 3가지는 html안의 요소들을 보여주는 property들인데요.

다음과 같은 차이가 있습니다.

 

구분 내용
textContent tag는 빼고 아래의 요소들을 보여준다. (innerHTML은 innerHTML태그를 포함함)
- spacing(띄어쓰기)
- CSS hidden text
innerText 순수한 text content만 필요할 때 사용
textContent처럼 글자앞에 spacing이 있더라도 제외하고 텍스트로 시작되는 값을 돌려준다.
innerHtml textContent에 innerHTML태그를 포함하는 버전이라고 보면 됨
- spacing
- innerHTML 태그

 

 

2-3. lastChild 와 firstChild

이름에서 알 수 있듯이 element의 마지막 자식과 첫번째 자식을 의미합니다.

 

document.getElementById("li").firstChild.innerHTML;
document.getElementById("li").lastChild.innerHTML;

 

2-4. nextSibling 과 previousSibling

list 아이템에서 다음 리스트의 html컨텐트를 보여줍니다.

 

document.getElementById("item1").nextSibling.textContent;

document.getElementById("item1").previousSibling.textContent;

 

2-5. nodeName

nodeName을 얻어올 수 잇는 프로퍼티입니다.

 

 

2-6. getElementsByClassName 과 getElementsByTagName

css selector를 사용하는 것은 아니지만,

클래스이름이나 태그이름으로 찾도록 해주므로 같이 사용하게 됩니다.

주의할 점은 리턴값이 forEach함수를 가지지 않는 HTML컬렉션 이라는 것 입니다.

이 함수에 forEach를 사용하고자 한다면, 아래와 같이 해 주면 됩니다.

 

const result = element.getElementsByClassName('test');
Array.from(result).forEach(e => console.log(e))

 

3. 팁 

3-1. 브라우저에서 Selector 테스트

CSS Selector들에 대해서는 언제나 브라우저에서 테스트가 가능하므로 테스트해 보는 것이 좋습니다.

특히 여러개의 요소가 있을 때는 어떤 attribute를 가져와야 할지를 알 수 있어서 더욱 좋습니다.

 

 

 

 

Selector를 미리 검증해 놓으면 개발하는 시간을 많이 줄여놓을 수 있으므로 매우 효율적입니다.

 

728x90

댓글