CSS 셀렉터 문법
CSS에서는 스타일을 적용할 대상을 선택하기 위해서 선택자(selector)를 사용하며 대표적으로 id 선택자, 태그 선택자, 클래스 선택자가 있다.
예제를 통해 살펴보자
아래의 html을 대상으로 셀렉터에 대해 알아보자.
<div class="container">
<h1>CSS 셀렉터 문법</h1>
<p>셀렉터 문법에 대해서 알아보자</p>
<div class = "article">
<h2 id="tag">태그로 찾기</h2>
<p>getElementsByTagName()</p>
</div>
<div class = "article">
<h2>클래스 속성값으로 찾기</h2>
<p>getElementsByClassName()</p>
</div>
<div class = "article">
<h2>id 값으로 찾기</h2>
<p id='test'>getElementsById()</p>
<input class="form-control" type="text" value="입력">
<input type="password" value="1234" id="password">
</div>
</div>
html 문서에서 요소(element)를 찾는 방법은 여러가지가 있다.
// article 클래스 속성값을 가진 요소의 내부 안에 있는 p태그 내용 출력
const articleClasses = document.getElementsByClassName('article');
for(const articleElement of articleClasses){
const paragraphElements = articleElement.getElementsByTagName('p');
for(const pElements of paragraphElements){
console.log(pElements.textContent)
}
}
// article 클래스 속성값을 가진 요소의 내부 안에 있는 p태그 내용 출력
const paragraphElements = document.querySelectorAll('.article p')
for(const paragraphElement of paragraphElements){
console.log(paragraphElement.textContent)
}
위의 예제와 같이 getElementsByTagName(), getElementsByClassName(), getElementsById()와 querySelectorAll()가 있는데 첫번째 예제에서 보이는 함수들은 간단한 조건만으로 요소를 찾는데 유용하고 복잡한 조건을 검색하는 것은 쉽지 않다.
1. 기본 셀렉터
Document.querySelector()는 선택된 선택자 또는 선택자 그룹과 일치하는 문서 내 첫 번째 Element를 반환한다. 일치하는 요소가 없으면 null을 반환한다.
Document.querySelectorAll()는 선택된 선택자 그룹에 일치하는 도큐먼트의 엘리먼트 리스트를 나타내는 NodeList를 반환한다.
1-1. 태그 셀렉터
console.log(document.querySelectorAll('p')); // NodeList(5) [p, p, p, p, p]
1-2. ID 셀렉터
console.log(document.querySelectorAll('#tag')); // NodeList [h2#tag]
1-3. 클래스 셀렉터
console.log(document.querySelectorAll('.article')); //NodeList(3) [div.article, div.article, div.article]
1-4. 속성 셀렉터
// value라는 속성을 가진 요소 검색
console.log(document.querySelectorAll('[value]')); // NodeList(2) [input.form-control, input]
// value의 속성 값이 1234인 요소 검색
console.log(document.querySelectorAll('[value="1234"]')); // NodeList [input]
2. 셀렉터 조합하기
2-1. OR 조건으로 찾기
여러 셀렉터를 ,로 연결하면 각 조건을 만족하는 요소 모두를 검색
// h1 태그 또는 input 태그 찾기
console.log(document.querySelectorAll('h1 ,input')); // NodeList(3) [h1, input.form-control, input#password]
2-2. AND 조건으로 찾기
다른 종류의 기본 셀렉터를 띄어쓰기 없이 이어붙이면 해동 조건들을 동시에 만족하는 요소를 검색. 이어 붙일 때 태그 셀렉터가 제일 앞에 나와야 하고 클래스 셀렉터나 속성 셀렉터는
// div 태그에 article 클래스 속성값이 지정된 요소 검색
console.log(document.querySelectorAll('div.article'));
// input 태그에 id 속성값이 password이고 type 속성값이 password인 요소 검색
console.log(document.querySelectorAll('input[type="password"]#password'));
3. 계층 구조 조합하기
3-1. 계층 순서로 요소 찾기
여러 셀렉터를 공백으로 연결하면, 연결된 순서대로 부모/자식 계층 관계를 가지는 요소를 검색
// div 태그를 상위 요소로 가진 모든 p 태그 요소 검색
console.log(document.querySelectorAll('div p')) // NodeList(5) [p, p, p, p, p]
// div 태그를 상위 요소로 두 번 가진 모든 p 태그 요소 검색
console.log(document.querySelectorAll('div div p')) // NodeList(4) [p, p, p, p]
3-2. 직접적인 자식 요소 찾기
여러 기본 셀렉터를 > 기호를 사용해 연결하면 부모/자식 계층 관계를 가지는 요소를 검색
// container 클래스 속성 값을 가진 div 요소의 직접적인 자식 중 p 태그 요소 검색
console.log(document.querySelectorAll('div.container > p')) // NodeList [p]
3-3. 동일한 부모를 가진 요소 찾기
여러 기본 셀렉터를 ~ 기호를 사용하여 연결하면 찾은 요소를 기준으로 동일한 부모를 갖는 조건을 만족하는 모든 요소 검색
// id가 test인 요소와 동일한 부모를 가진 input 태그 요소 검색
console.log(document.querySelectorAll('#test ~ input')) // NodeList(2) [input.form-control, input#password]
3-4. 동일한 부모를 가지면서 인접한 요소 찾기
여러 기본 셀렉터를 + 기호를 사용하여 연결하면 찾은 요소를 기준으로 동일한 부모를 가지면서 해당 요소 바로 다음에 나오는 요소 하나를 검색
// id가 test인 요소와 동일한 부모를 가진 input 태그 요소 검색
console.log(document.querySelectorAll('#test + input')) // NodeList [input.form-control]
'HTML&CSS' 카테고리의 다른 글
[CSS] display, position (0) | 2021.11.29 |
---|