< Code diaries />

Javascript로 html 요소의 컨텐츠 가져오기, 수정하기(innerHTML, textContent, innerText) 본문

Javascript-DOM/02 - DOM 다루기

Javascript로 html 요소의 컨텐츠 가져오기, 수정하기(innerHTML, textContent, innerText)

ejey 2024. 6. 2. 22:27

 

 

오늘은 javascript에서 어떻게 HTML 요소의 값을 다루는지 살펴보아요~
렛츠가.. 기릿입니다... (흐흐흐 아시는분은 다 아시는 구호죠? 돌비채널 팬이라.. )




아래의 간단한 HTML 마크업으로 한번 해 봅시다~

<h1 class="title"><strong>See</strong> My fruite</h1>
<figure class="thumb"> 
   <img src="./tomato.jpg" alt="tomato">
   <figcaption>토마토</figcaption>
</figure>

 

INIT - 먼저 html 요소를 변수에 담아옵니다.

const title = document.querySelector('.title');
const img = document.querySelector('.thumb img');
const caption = document.querySelector('.thumb figcaption');

 

 

Property List

Property type description
textContent Node script, style 적용여부와 상관없이 공백포함 모든 textNode를 가져온다.
innerHTML Element 태그와 텍스트를 포함한 모든것을 가져온다.
innerText Element 브라우저에 렌더링되는 text를 가져온다.

 

 

여기서 잠깐~!

textContent와 innerText는 둘다 텍스트를 가져오는데 무슨차이가 있나요?

innerText는 브라우저가 텍스트를 렌더링 한 후의 모습을 인식하여서 css에서 숨기거나 한 글들은 가져오지 않습니다. 하지만 textContent는 css를 인식하지 않기때문에 해당 Node의 텍스트를 모두 출력합니다. 

 

 

 

A. innerHTML로 가져오기 - <h1>의 제목을 가져와 출력해보자.

const value = title.innerHTML;
console.log(value);

// output - h1의 컨텐츠 출력. 이때 태그가 있을경우 같이 출력함.
// <strong>See</strong> My fruite

 

B. innerHTML로 수정하기 - <h1>의 제목을 바꾸어 봅시다.

title.innerHTML = '<a href="#">See</a> My Fruite';  

// output - 마크업변경
<h1>
   <a href="#">See</a> My Fruite
</h1>

 

C. textContent로 가져오기 - <figcaption>의 내용을 가져와 출력해보자

const newCaption = caption.textContent;

// output - <figure>태그의 contents 중 텍스트와 공백을 출력한다.
// 토마토

 

D. textContent로 수정하기 - <h1>의 제목을 출력하여 <figcaption>에 넣어주자.

caption.textContent = title.textContent + 'It is delicious, right?';

// output -> <h1>의 텍스트컨텐츠를 가져온 후, 추가한 문장을 붙인다.
<figcaption>
	See My Fruite. It is delicious, right?
</figcaption>

E. innerText는 위의 textContent와 사용이 동일하다.

 

 

Reference

 

HTMLElement.innerText - Web API | MDN

HTMLElement 인터페이스의 innerText 속성은 요소와 그 자손의 렌더링 된 텍스트 콘텐츠를 나타냅니다. innerText는 사용자가 커서를 이용해 요소의 콘텐츠를 선택하고 클립보드에 복사했을 때 얻을 수

developer.mozilla.org

 

반응형

'Javascript-DOM > 02 - DOM 다루기' 카테고리의 다른 글

Javascript로 DOM 접근하기  (0) 2024.06.02