[JavaScript] iOS에서 innerText 사용할 때 주의할 점

Yeonsu Summer·2022년 12월 2일
0

JavaScript

목록 보기
7/13
post-thumbnail

저는 요즘 식메추(https://sikmechu.vercel.app/)라는 메뉴 추천 프로그램을 만들고 있습니다.

모바일에서 사용하는 웹이다보니 MacOS, WindowOS 뿐만 아니라 AndroidOS와 iOS의 환경에서도 잘 돌아가도록 구현을 해야합니다.

저는 이 프로젝트를 진행하면 iOS 환경에서 두 번의 쓴 맛을 겪었습니다.

그 중 하나는 오늘 소개할 innerText 입니다.


문제점

<!-- HTML -->
<button class="option-button" type="button">
  직접 요리
  <img src="./assets/icon-cook.svg" alt="" />
</button>
// JavaScript
const button = document.querySelector(".option-button")
const type = typeButton.innerText;
console.log(type);
console.log(typeof type);
console.log(type === "직접 요리");

WindowOS, MacOS, AndroidOS 결과

직접 요리
string
true

iOS 결과

직접 요리
string
false

innerText 값과 타입은 동일하게 나오는데 type === "직접 요리"는 다르게 나올까요?

이유

문제점은 자바스크립트가 아닌 HTML 줄바꿈에 있었습니다.

<!-- HTML -->
<button class="option-button" type="button">
  직접 요리 <!-- 여기 줄바꿈 -->
  <img src="./assets/icon-cook.svg" alt="" />
</button>

저는 코드를 깔끔하게 하기 위하여 텍스트 다음에 줄바꿈 하고 img 태그를 넣었습니다.

iOS에서 button 태그의 innerText직접 요리 가 아닌 직접 요리 와 같이 뒤에 띄어쓰기 하나가 추가된 것 입니다.

콘솔에서는 뒤에 띄어쓰기가 있는지 없는지 구분하기 어려워서 이 부분을 찾는데 오래 걸렸습니다 😅

해결책

  1. 텍스트 다음 줄바꿈을 생략합니다.
<!-- HTML -->
<button class="option-button" type="button">
  직접 요리<img src="./assets/icon-cook.svg" alt="" />
</button>
// JavaScript
// 자바스크립트 코드는 동일합니다.
  1. 저는 태그마다 줄바꿈을 하는 것을 선호하기 때문에 이 방식을 선택하였습니다.
<!-- HTML -->
<button class="option-button" type="button">
  <span>직접 요리</span>
  <img src="./assets/icon-cook.svg" alt="" />
</button>
// JavaScript
const button = document.querySelector(".option-button")
const type = typeButton.firstElementChild.innerText;
console.log(type);
console.log(typeof type);
console.log(type === "직접 요리");

WindowOS, MacOS, AndroidOS, iOS 결과

직접 요리
string
true


iOS는 뭔가 특별한 운영체제 같습니다. 특별히 뭔가 다르고 뭔가 짜쯩

profile
🍀 an evenful day, life, journey

0개의 댓글