프로젝트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

자바스크립트 요소 접근방법 - getElementsByClassName()

 


자바스크립트에서 html 요소에 접근하는 방법 중 class 를 이용하는 방법이다.
바로 document 객체의 getElementsByClassName() 메소드 이다.

코드를 보자.
<h1>The Document Object</h1>
  <h2>The getElementsByClassName() method</h2>

  <p>Change the text of the first elements with
class ="example"</p>

  <div class="example">Element1</div>
  <div class="example">Element1</div>

  <script>
    const collection = document.getElementsByClassName("example");
    collection[0].innerHTML = "Good Morning!"
  </script>

div 요소 두개의 class 네임이 example 이다.
이 두개의 요소에 접근하여 첫번째 요소의 콘텐츠 값을 변경하려고 한다.

핵심은 바로 document.getElementsByClassName() 메소드의 인자값으로
class 속성의 값을 지정해준다.

document.getElementsByClassName("example");

그럼, 해당 인자값 즉 class 를 가진 HTML 요소를 문서에서 찾아 반환한다.
console.log 로 반환값을 찍어보면, 하기처럼 HTMLCollection이라는 배열 타입을 반환하는 것으로 보인다. 정확히 말하면 HTMLCollection 은 배열과 유사한 모양을 가진 객체이다.

  1. HTMLCollection(2) [div.example, div.example]
    1. length: 2


반환값을 받은 collection 이란 객체 변수는 
배열처럼 collection[0].innerHTML 첫번째 요소에 접근하여 콘텐츠 값을 수정할 수 있다.
그러므로, 위 코드의 결과는 다음과 같다.

The Document Object

The getElementsByClassName() method

Change the text of the first elements with class ="example"

Good Morning!
Element1

댓글

이 블로그의 인기 게시물

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

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

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