프로젝트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 요소 접근 querySelector() 함수 사용하기

 


querySelector() 함수를 사용해서 HTML요소에 접근 해본다
querySelector()함수의 인자는 CSS선택자 가 들어간다.
코드를 보자.

 <h1>The Document Object</h1>
  <h2 class="text">The querySelector() Method</h2>

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

  <script>
    const one = document.querySelector("p")
    one.style.background = "red";
    const two = document.querySelector(".text");
    two.style.background = "green";
  </script>

핵심은 document.querySelector() 메서드 이다. 
반환 값으로 해당 요소 하나만을 반환한다. 
위코드에서는 

요소.style.속성 

으로 스타일을 지정하고 있다.
document.querySelector() 메서드 의 인자로는 CSS 선택자 가 온다.

추가로, querySelectorAll() 메서도 도 알아보자.
메서드 이름에서 들어나듯 반환값이 하나가 아니고 여러개임을 유추할 수 있다.
코드를 보자. 

  <h1 class="text">The Document Object</h1>
  <h2 class="text">The querySelector() Method</h2>

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

  <script>
    const one = document.querySelectorAll("p")
    one.forEach(element => {
      element.style.background='red';
    });
    const two = document.querySelectorAll(".text");
    two.forEach(element => {
      element.style.background='green';
    });
  </script>

핵심인 querySelectorAll() 메서드의 반환값은 여러개의 요소를 반환하며,
nodeList 라는 배열형태의 객체에 요소들을 담고 있다.
위 코드에서는 forEach 메소드를 사용해서 각각의 nodeList 에 등록된 요소의 스타일을
수정하고 있다.

웹 브라우저에서 확인한 결과는 아래와 같다.

The Document Object

The querySelector() Method

Add a background color to the first p element

This is first p element

This is second p element


CSS 선택자를 사용해서 요소를 선택할때
1. 하나의 요소만 원한다면
querySelector() 를 사용하고

2. 여러개의 요소라면
querySelectorAll() 메소드를 사용하자.

댓글

이 블로그의 인기 게시물

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

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

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