JS BASIC | value, textContent, innerHTML, innertext

chaen·2023년 7월 6일
0

JS Grammar

목록 보기
12/28
post-thumbnail

입력된 텍스트 값을 가져와서 변경할 때 네 가지 기능을 사용한다.

value

  • input, select, textarea과 같은 form 요소의 값을 가져오고 싶을 때 사용한다.
  • value에 값을 대입하면 대입한 값으로 변경된다.
input.value // 입력창의 값을 가져옴
input.value =// 입력창에 값을 넣음

textContent

  • textContent는 'Node'의 속성이다.
  • innetText와는 달리 <script><style> 태그와 상관없이 해당 노드가 가지고 있는 텍스트 값을 그대로 읽는다.
    • display:none 스타일이 적용된 '숨겨진 텍스트' 문자열도 그대로 출력된다.
    • 연속된 공백이 그대로 보여진다.
  • 속성: 문자열, 숫자로 가져오고 싶을 때는 number로 감싸줘야 한다.

innerHTML

  • innerHTML은 'Element'의 속성이다.
  • 해당 ElementHTML, XML을 읽어오거나, 설정할 수 있다.
  • textContent와 같이, div 안의 HTML 전체 내용을 가져 온다. (숨겨진 텍스트 등 포함)
const element = document.getElementById('content');
console.log(element.innerHTML);

//<div>A</div>
//<div>B</div>

innerText

  • innerText는 'Element'의 속성이다.
  • 해당 Element 내에서 사용자에게 '보여지는' 텍스트 값을 읽어온다.
  • 내용에 연속되는 공백이 있다면 연속공백을 무시하고 하나의 공백만 처리하여 보여진다.
  • display : none; 한 값들은 불러들이지 않는다.
const element = document.getElementById('content');
console.log(element.innerText);

//A
//B

값을 삽입할 때, innerText vs innerHTML

const element = document.getElementById('content');
  element.innerText = "<div style='color:red'>A</div>";
// <div style='color:red'>A</div>
  element.innerHTML = "<div style='color:red'>A</div>";
// A (color: red인)

1분 퀴즈

다음 태그들의 내부 값을 가져올 때 둘 중 어떤 속성을 사용해야 하는지 표시해 보세요.

① input (value / textContent)

② button (value / textContent)

③ select (value / textContent)

④ div (value / textContent)

⑤ textarea (value / textContent)

⑥ span (value / textContent)

0개의 댓글