프로젝트4 - div 섹션 구역 분리 와 CSS 스타일 적용하기

이미지
웹 브라우저에 표시되는 글자와 이미지 들에 디자인 적인 효과( 배경색, 글자색, 크기 조절...) 및 브라우저 내에서의 배치등을 조절하기 위해서는 구역을 나누면 편리해진다. 바로 구역(섹션) 을 나누어 주는 역할을 하는 태그가 div 이다. <div>태그는 브라우저에서 보여지는 시각적 기능은 없다. 단지, 구역을 나누는 역할을 한다.  코드를 만들어 본다. <!DOCTYPE html> <html> <head>   <title>div</title> </head> <body>   <div>     <p>Ice cream is a frozen dessert typically made from milk or cream that has been flavoured with a sweetener,        either sugar or an alternative, and a spice,        such as cocoa or vanilla, or with fruit, such as strawberries or peaches.</p>   </div>   <div>     <p> Food colouring is sometimes added in addition to stabilizers.        mixture is cooled below the freezing point of water and stirred to incorporate air spaces and prevent detectable ice crystals from forming.        It can also be made by whisking a flavoured cream base and liquid nitrogen together.        The result is a smooth, semi-solid foam that is solid at v

자바스크립트 HTML요소 접근하기 - CSS 선택하기

 


자바스크립트 에서 HTML요소 에 접근하기 위한 방법으로는
CSS 선택자를 활용하는 방법이 있다.
역시 코드를 보자.
  <h1>The Document Object</h1>
  <h2>The querySelector() Method</h2>

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

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

핵심은 바로,

document.querySelector("p")

메소드 이다. 인자로 CSS 선택자를 적는다. 
querySelector() 메소드는 해당 선택자로 선택된 모든 요소 중 첫번째 요소만 가져온다.
콘솔로그에 찍힌 값은 하기와 같이 첫째 줄의 요소만 가지고 온다.

<p>This is a first p element</p>

가져온 요소의 배경색상을 바꾸는 코드를 적용하면 

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

하기와 같은 결과가 나온다.

The Document Object

The querySelector() Method

Add a background color to the first p element:

This is a first p element

This is a second p element


그럼 여기서, 선택자로 선택된 모든 요소를 가지고 오려면?
바로 querySelectorAll() 메소드를 사용한다. 해당 메소드 의 반환값은 nodelist 형 객체 이며, HTML요소 들을 노드 단위로 반환한다.  위 코드를 하기처럼 바꾸자
 <script>
    let nodeList = document.querySelectorAll("p");
    console.log(nodeList);
    for(let i=0; i < nodeList.length ; i++){
      nodeList[i].style.backgroundColor = "red";
    }
  </script>  

document.querySelectorAll() 메소드의 반환 값은 NodeList 객체 타입이다.
그 객체는 배열처럼 선택자로 선택된 "노드" 들을 가지고 있다.
  1. NodeList(2) [p, p]
    1. length: 2

for 문으로 각 요소에 접근하여 색상을 교체한다. 

This is a first p element

This is a second p element

document.selector() 는 CSS 선택자 로 하나의 요소에 접근할때 유리하며,

document.selectorAll() 은 CSS 선택자로 여러개의 요소에 접근할때 사용한다.

댓글

이 블로그의 인기 게시물

구글 블로그 이미지 복사 붙여넣기 가능한가요?

HTML 페이지 기본 구성.(HTML Page Structure)

구글 블로그 대표이미지 설정하기