230128_TIL

·2023년 2월 6일
0

innerHTML

  • Element속성. Element내에 포함된 HTML or XML 마크업을 가져오거나 태그와 함께 입력하여 내용을 직접 설정할 수 있음.
  • DOM을 직접적으로 조작. 내부 HTML 코드를 JS코드에서 새 내용으로 쉽게 변경 가능하다.
// html 태그를 이용하여 직접 html에 작성 가능하다. (DOM 조작)
document.documentElement.innerHTML = "<p>innerHTML</p>"
// 스타일 적용
document.documentElement.innerHTML = 
  "<span style='color:blue'>innerHTML</span>"
// 이런 식으로 빈 문자열을 넣으면 body의 전체 내용을 지울 수 있다.
document.body.innerHTML = "";

innerText

  • innerHTML과 동일하게 Element 속성. 사용자에게 보여지는 text값들을 가져오거나 설정 가능.
// innerHTML과 달리 text값만 다룬다. html태그 사용 불가능
document.documentElement.innerText = "innerText(넣을 텍스트를 입하면된다)"

// html태그를 넣으면 태그도 text값으로 인식하고 
// <p>innerText</p> 문자열 그대로 적용함.
document.documentElement.innerText = "<p>innerText</p>"
  • innerHTML VS innerText
const innerT = document.getElementById('innerT');
innerT.innerText = "<div style='color:red'>innerText</div>";
console.log(innerT)
// 스타일 적용되지 않은 기본 폰트로 <div style='color:red'>innerText</div> 출력

const innerH = document.getElementById('innerH');
innerH.innerHTML = "<div style='color:red'>innerHTML</div>";
console.log(innerH)
// 스타일 적용된 빨간색 폰트로 innerHTML 출력

textContent

  • Element가 아닌 Node속성이다. 사용자에게 보여지는 text값만 읽어오는 innerText와는 달리 <script>, <style>태그에 상관없이 해당 노드가 가지고 있는 텍스트 값을 모두 읽어온다.
  • display : none; 으로 숨겨진 텍스트를 어떻게 가지고 오는지 각 속성의 차이점을 알 수 있음

HTML

<div id='content'>
  안녕~ 
  <span style='display:none'>innerText는 인식하지 못한다.</span>
</div>

script

const content = document.getElementById('content');

console.log(content.innerHTML);
// html 전체를 다 가져옴 (태그까지 전부 다 가져옴)

// 안녕~ 
// <span style='display:none'>innerText는 인식하지 못한다.</span>

-----------------------------------------------------
  
console.log(content.innerText);
// 사용자에게 보여지는 텍스트만 가져옴
// 숨겨진 텍스트는 사용자에게 보여지지 않기 때문에 안녕~만 가져옴

// 안녕~

-----------------------------------------------------
  
console.log(content.textContent);
// 숨겨진 텍스트까지 포함해서 텍스트값을 모두 다 가져옴

// 안녕~
// innerText는 인식하지 못한다.

차이점

  • innerHTML과 innerText과 textContent 차이
  1. innerHTML은 요소 내에 있는 HTML과 XML 모두를 의미
  2. innerText는 요소 내에서 사용자에게 보여지는 text를 의미
  3. textContent는 script나 style 태그와 상관없이 해당 노드가 가지고 있는 text를 의미

new Set()

  • Set 객체는 ES6에서 등장한 중복을 제거한 값들의 집합이다.

0개의 댓글