데이터 속성으로 요소 선택
data
속성 에 따라 요소를 선택하는 쉽고 간단한 방법이 있습니까? 예를 들어 customerID
값 이라는 이름의 데이터 속성이있는 모든 앵커를 선택합니다 22
.
나는 rel
그러한 정보를 저장 하기 위해 또는 다른 속성 을 사용하는 것을 주저 하지만 어떤 데이터가 저장되어 있는지에 따라 요소를 선택하는 것이 훨씬 더 어렵다는 것을 알았습니다.
$('*[data-customerID="22"]');
를 생략 할 수 *
있지만 올바르게 기억하면 사용중인 jQuery 버전에 따라 잘못된 결과를 얻을 수 있습니다.
선택기 API ( document.querySelector{,all}
) 와의 호환성을 위해이 경우 속성 값 ( 22
) 주위의 따옴표를 생략 할 수 없습니다 .
또한 jQuery 스크립트에서 데이터 속성을 많이 사용하는 경우 HTML5 사용자 정의 데이터 속성 플러그인 사용을 고려할 수 있습니다 . 이렇게하면을 사용하여 훨씬 더 읽기 쉬운 코드를 작성할 수 있으며 .dataAttr('foo')
축소 후 파일 크기가 더 작아집니다 (를 사용하는 것에 비해 .attr('data-foo')
).
인터넷 검색을하고 데이터 속성으로 선택하는 것에 대한보다 일반적인 규칙을 원하는 경우 :
$("[data-test]")
단지 어느 한 요소를 선택한다 갖는 데이터 속성이 (어떠한 속성의 값을 상관 없음). 포함 :
<div data-test=value>attributes with values</div>
<div data-test>attributes without values</div>
$('[data-test~="foo"]')
다음과 같이 데이터 속성에 포함 foo
되지만 정확할 필요는없는 요소를 선택합니다 .
<div data-test="foo">Exact Matches</div>
<div data-test="this has the word foo">Where the Attribute merely contains "foo"</div>
$('[data-test="the_exact_value"]')
데이터 속성 정확한 값이 the_exact_value
인 모든 요소를 선택합니다 . 예를 들면 다음과 같습니다.
<div data-test="the_exact_value">Exact Matches</div>
하지만
<div data-test="the_exact_value foo">This won't match</div>
을 사용 $('[data-whatever="myvalue"]')
하면 html 속성을 가진 모든 것이 선택되지만 최신 jQueries에서는 $(...).data(...)
데이터를 첨부하는 데 사용하는 경우 마법의 브라우저를 사용하고 html에 영향을 미치지 않으므로 이전 답변에.find
표시된대로 발견되지 않습니다 .
확인 (1.7.2+로 테스트 됨) ( fiddle 도 참조 ) : (더 완전하게 업데이트 됨)
var $container = $('<div><div id="item1"/><div id="item2"/></div>');
// add html attribute
var $item1 = $('#item1').attr('data-generated', true);
// add as data
var $item2 = $('#item2').data('generated', true);
// create item, add data attribute via jquery
var $item3 = $('<div />', {id: 'item3', data: { generated: 'true' }, text: 'Item 3' });
$container.append($item3);
// create item, "manually" add data attribute
var $item4 = $('<div id="item4" data-generated="true">Item 4</div>');
$container.append($item4);
// only returns $item1 and $item4
var $result = $container.find('[data-generated="true"]');
data 속성이있는 모든 앵커를 선택하려면를 data-customerID==22
포함 a
하여 검색 범위를 해당 요소 유형으로 만 제한 해야 합니다. 페이지에 많은 요소가있을 때 큰 루프 또는 높은 빈도로 데이터 속성 검색을 수행하면 성능 문제가 발생할 수 있습니다.
$('a[data-customerID="22"]');
jQuery 없이는 JavaScript 답변을 보지 못했습니다. 누군가에게 도움이되기를 바랍니다.
var elements = document.querySelectorAll('[data-customerID="22"]');
elements[0].innerHTML = 'it worked!';
<a data-customerID='22'>test</a>
정보 :
Native JS Examples
Get NodeList of elements
var elem = document.querySelectorAll('[data-id="container"]')
html: <div data-id="container"></div>
Get the first element
var firstElem = document.querySelectorAll('[id="container"]')[0]
html: <div id="container"></div>
Target a collection of nodes which returns a nodelist
document.getElementById('footer').querySelectorAll('[data-id]')
html:
<div class="footer">
<div data-id="12"></div>
<div data-id="22"></div>
</div>
Get elements based on multiple (OR) data values
document.querySelectorAll('[data-section="12"],[data-selection="20"]')
html:
<div data-selection="20"></div>
<div data-section="12"></div>
Get elements based on combined (AND) data values
document.querySelectorAll('[data-prop1="12"][data-prop2="20"]')
html:
<div data-prop1="12" data-prop2="20"></div>
Get items where the value starts with
document.querySelectorAll('[href^="https://"]')
via Jquery filter() method:
http://jsfiddle.net/9n4e1agn/1/
HTML:
<button data-id='1'>One</button>
<button data-id='2'>Two</button>
JavaScript:
$(function() {
$('button').filter(function(){
return $(this).data("id") == 2}).css({background:'red'});
});
The construction like this: $('[data-XXX=111]')
isn't working in Safari 8.0.
If you set data attribute this way: $('div').data('XXX', 111)
, it only works if you set data attribute directly in DOM like this: $('div').attr('data-XXX', 111)
.
I think it's because jQuery team optimized garbage collector to prevent memory leaks and heavy operations on DOM rebuilding on each change data attribute.
For this to work in Chrome the value must not have another pair of quotes.
It only works, for example, like this:
$('a[data-customerID=22]');
It's sometimes desirable to filter elements based on whether they have data-items attached to them programmatically (aka not via dom-attributes):
$el.filter(function(i, x) { return $(x).data('foo-bar'); }).doSomething();
The above works but is not very readable. A better approach is to use a pseudo-selector for testing this sort of thing:
$.expr[":"].hasData = $.expr.createPseudo(function (arg) {
return function (domEl) {
var $el = $(domEl);
return $el.is("[" + ((arg.startsWith("data-") ? "" : "data-") + arg) + "]") || typeof ($el.data(arg)) !== "undefined";
};
});
Now we can refactor the original statement to something more fluent and readable:
$el.filter(":hasData('foo-bar')").doSomething();
Just to complete all the answers with some features of the 'living standard' - By now (in the html5-era) it is possible to do it without an 3rd party libs:
- pure/plain JS with querySelector (uses CSS-selectors):
- select the first in DOM:
document.querySelector('[data-answer="42"],[type="submit"]')
- select all in DOM:
document.querySelectorAll('[data-answer="42"],[type="submit"]')
- select the first in DOM:
- pure/plain CSS
- some specific tags:
[data-answer="42"],[type="submit"]
- all tags with an specific attribute:
[data-answer]
orinput[type]
- some specific tags:
참고URL : https://stackoverflow.com/questions/2487747/selecting-element-by-data-attribute
'Programing' 카테고리의 다른 글
Java에서 JSON을 구문 분석하는 방법 (0) | 2020.09.28 |
---|---|
Rails 정품 토큰 이해 (0) | 2020.09.28 |
로컬 저장소와 쿠키 (0) | 2020.09.28 |
Node.js + Nginx-이제 무엇입니까? (0) | 2020.09.28 |
주문 후 Oracle 쿼리에서 반환되는 행 수를 어떻게 제한합니까? (0) | 2020.09.28 |