getAttribute () 대 Element 객체 속성?
식은 똑같은 것을 좋아 Element.getAttribute("id")
하고 Element.id
반환합니다.
HTMLElement 객체의 속성이 필요할 때 어떤 것을 사용해야합니까?
getAttribute()
및 같은 이러한 방법에 크로스 브라우저 문제가 setAttribute()
있습니까?
아니면 객체 속성에 직접 액세스하는 것과 이러한 속성 메서드를 사용하는 것 사이의 성능에 어떤 영향을 미칩니 까?
getAttribute
검색 속성 , 동안 DOM 요소를 el.id
검색하는 속성 이 DOM 요소한다. 그들은 동일하지 않습니다.
대부분의 경우 DOM 속성은 속성과 동기화됩니다.
그러나 동기화 가 동일한 값을 보장하지는 않습니다 . 고전적인 예는 앵커 요소 사이 el.href
와 el.getAttribute('href')
입니다.
예를 들면 :
<a href="/" id="hey"></a>
<script>
var a = document.getElementById('hey')
a.getAttribute('href') // "/"
a.href // Full URL except for IE that keeps '/'
</script>
이 동작은 W3C 에 따라 href 속성이 올바른 형식의 링크 여야 하기 때문에 발생 합니다. 대부분의 브라우저는이 표준을 존중합니다 (누가 그렇지 않을까요?).
input
의 checked
재산에 대한 또 다른 사례가 있습니다. DOM 속성은 true
또는 false
속성이 문자열 "checked"
또는 빈 문자열을 반환하는 동안 반환 합니다.
그리고 단방향으로 만 동기화되는 일부 속성이 있습니다 . 가장 좋은 예는 요소 의 value
속성입니다 input
. DOM 속성을 통해 값을 변경해도 속성은 변경되지 않습니다 (편집 : 더 정확한 첫 번째 주석 확인).
이러한 이유 때문에 브라우저마다 동작이 다르기 때문에 속성이 아닌 DOM 속성 을 계속 사용하는 것이 좋습니다 .
실제로 속성을 사용해야하는 경우는 두 가지뿐입니다.
- DOM 속성에 동기화되지 않기 때문에 사용자 정의 HTML 속성입니다.
- 속성에서 동기화되지 않은 기본 제공 HTML 속성에 액세스하려면 속성 (예
value
:input
요소 의 원본 )이 필요합니다.
더 자세한 설명을 원하시면 이 페이지 를 읽어 보시기 바랍니다 . 몇 분 밖에 걸리지 않지만 정보 (여기서 요약 한 내용)에 기뻐할 것입니다.
getAttribute('attribute')
일반적으로 페이지의 HTML 소스에 정의 된대로 속성 값을 문자열로 반환합니다.
그러나 element.attribute
속성의 정규화 또는 계산 된 값을 반환 할 수 있습니다. 예 :
<a href="/foo"></a>
- a.href는 전체 URL 을 포함합니다.
<input type="checkbox" checked>
- input.checked는 true (부울)가됩니다.
<input type="checkbox" checked="bleh">
- input.checked는 true (부울)가됩니다.
<img src='http://dummyimage.com/64x64/000/fff'>
- img.width는 이미지가로드되기 전에 0 (숫자) 이됩니다.
- img.width는 이미지 (또는 이미지의 처음 몇 바이트)가로드 될 때 64 (숫자)가됩니다.
<img src='http://dummyimage.com/64x64/000/fff' width="50%">
- img.width는 계산 된 50 %가됩니다.
<img src='http://dummyimage.com/32x32/000/fff' style='width: 50px'>
- img.width는 50 (숫자)입니다.
<div style='background: lime;'></div>
- div.style은 객체가됩니다.
.id
함수 호출 오버 헤드를 저장합니다. (매우 작지만 물었다.)
이 jsPerf 테스트 에 따르면 속성 getAttribute
보다 느립니다 id
.
추신
이상하게도 두 명령문은 다른 브라우저에 비해 IE8에서 매우 나쁘게 수행됩니다.
특별한 이유가없는 한 항상 속성을 사용하십시오.
getAttribute()
andsetAttribute()
are broken in older IE (and compatibility mode in later versions)- properties are more convenient (in particular, those corresponding to boolean attributes)
There are some exceptions:
- accessing attributes of
<form>
elements - accessing custom attributes (although I'd discourage using custom attributes at all)
I've written about this subject a few times on SO:
Try below example to understand this completely. For the below DIV
<div class="myclass"></div>
The Element.getAttribute('class')
will return myclass
but you have to use Element.className
which retrieves it from the DOM property.
One area where this makes a big difference is with css styling based on attributes.
Consider the following:
const divs = document.querySelectorAll('div');
divs[1].custom = true;
divs[2].setAttribute('custom', true);
div {
border: 1px solid;
margin-bottom: 8px;
}
div[custom] {
background: #36a;
color: #fff;
}
<div>A normal div</div>
<div>A div with a custom property set directly.</div>
<div>A div with a custom attribute set with `setAttribute`</div>
The div with the custom property set directly doesn't reflect the value to the attribute, and is not selected by our attribute selector (div[custom]
) in the css.
The div with the custom attribute set using setAttribute
, however, is able to be selected using a css attribute selector, and styled accordingly.
참고URL : https://stackoverflow.com/questions/10280250/getattribute-versus-element-object-properties
'IT story' 카테고리의 다른 글
파이썬 문자열에서 3 개의 백 슬래시가 4와 같은 이유는 무엇입니까? (0) | 2020.09.05 |
---|---|
EclipseIDE에서 클래스의 모든 메서드에 메서드 중단 점 추가 (0) | 2020.09.05 |
Python의 내장 sort () 메서드 정보 (0) | 2020.09.05 |
Android에서 @SmallTest, @MediumTest 및 @LargeTest 주석의 목적은 무엇입니까? (0) | 2020.09.05 |
ng-model을 사용하여 날짜 형식을 지정하는 방법은 무엇입니까? (0) | 2020.09.05 |