프론트엔드 면접 질문 정리 [HTML #1 data 속성]

전창현·2020년 8월 14일
0

문법

1. HTML markup

<div id="dataSet" data-name='hello' data-index='1' data-camel-case='camelCase'>ex</div>

2. JS handling

const $div = document.querySelector('#dataSet');

1. 일반적인 HTMLElement API를 이용하는 방법 

**$**div.getAttribute('data-name') 
$div.setAttribute('data-name', 'hi')
$div.removeAttribute('data-name');

2. HTMLOrForeignElement API를 이용하는 방법

- HTML attributes가 DOMStringMap 형태로 변환된
- HTMLOrForeignElement.dataset의 key값을 통해 접근한다.

$div.dataset.name // read
$div.dataset[name] // read
$div.dataset.name = 'hi' // write
$div.dataset.camelCase // HTML attribute의 '-'는 camelCase property로 변환된다.
$div.dataset.index = 2 // '2' dataset의 key에 할당하는 값은 string으로 변환된다.
$div.dataset.index = null // 'null'

3. CSS styling

HTML

<div data-size="large">hello</div>
<div data-size="small">world</div>

CSS

[data-size]{
	color: red;
}
[data-size='small']{
	color: blue;
}

[from] ttps://css-tricks.com/almanac/selectors/a/attribute/

HTML attribute 셀렉터 정리

[data-value] {
  /* Attribute exists */
}

[data-value="foo"] {
  /* Attribute has this exact value */
}

[data-value*="foo"] {
  /* Attribute value contains this value somewhere in it */
	'foo-boo', 'slfoo'
}

[data-value~="foo"] {
  /* Attribute has this value in a space-separated list somewhere */
}

[data-value^="foo"] {
  /* Attribute value starts with this */
}

[data-value|="foo"] {
  /* Attribute value starts with this in a dash-separated list */
}

[data-value$="foo"] {
  /* Attribute value ends with this */
}

data 속성 활용 시 주의할 점

1. accessibility & SEO

data attribute는 접근성 지원이 되지 않으므로
visible, accessible한 내용들은 data-attribute를 통해 저장하지 않도록 한다.

검색 크롤러는 data attribute에 저장되는 index값을 읽어낼 수 없다.

2. 성능

IE 11+ 하위버전은 dataset을 지원하지 않으므로 getAttribute()를 사용하지 않도록 한다.

3. 올바른 활용 방법

위 특징들을 고려해

  1. 접근성과 무관하며

  2. 크롤러에 노출되지 않고 private하게 사용할 data를 처리할 떄 사용한다.

  3. 주로 DOM element를 traversing할 때 사용된다.

활용 방법

일반적으로 DOM traversing에 사용된다.

1. 다음과 같이 응용할 수 있으나, 접근성에 불리한 지양해야하는 활용 방법

<div data-emoji="😃">hello</div>
<div data-text="chang hyun">my name is</div>

[data-emoji]::before{
  content: attr(data-emoji);
  margin-right: 5px;
}

[data-text]::after{
  content: attr(data-text);
  margin-left: 5px;
}

2. JSON 형태의 데이터 저장

<li data-person='{
                  "name" : "jun",
                  "age" : "28"
                  }'></li>

const li = document.querySelector('li');

const {name, age} = JSON.parse(li.dataset.person);
li.textContent = name +' '+age ;

3. 부트스트랩 활용 예시 - 모달창을 제거하는 버튼

<button type="button" class="close" data-dismiss="modal" aria-label="Close">
  <span aria-hidden="true">&times;</span>
</button>

4. 부트스트랩 활용 예시 - collapsible element를 토글링하는 버튼

<p>
  <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
    Link with href
  </a>
  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Button with data-target
  </button>
</p>
<div class="collapse" id="collapseExample">
  <div class="card card-body">
    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
  </div>
</div>

4. data 속성을 활용한 collapsible element 구현

https://codepen.io/changhyun2/pen/KKVYLVG

reference
https://css-tricks.com/a-complete-guide-to-data-attributes/

https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset

https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset

0개의 댓글