속성 값을 기반으로 DOM에서 요소 찾기
주어진 속성 이름과 속성 값을 가진 요소를 검색하는 DOM API가 있는지 알려주세요.다음과 같은 것 :
doc.findElementByAttribute("myAttribute", "aValue");
업데이트 :
지난 몇 년 동안 풍경이 크게 바뀌 었습니다. 이제 안정적으로 사용할 수 있습니다
querySelector
및
querySelectorAll
참조
이 작업을 수행하는 방법에 대한합니다.이제 jQuery 종속성이 필요하지 않습니다. jQuery를 사용하는 경우 훌륭합니다 ... 사용하지 않으면 더 이상 속성별로 요소를 선택하는 데 의존 할 필요가 없습니다.
바닐라 자바 스크립트 에서이 작업을 수행하는 매우 짧은 방법은 없지만 몇 가지 솔루션이 있습니다.
요소를 반복하고 속성을 확인하여 이와 같은 작업을 수행합니다.
와 같은 라이브러리 가 옵션 이라면 다음과 같이 조금 더 쉽게 할 수 있습니다.
$("[myAttribute=value]")
값이 유효한
가 아닌 경우 (공백 또는 문장 부호 등) 값 주위에 따옴표가 필요합니다 (단일 또는 이중 일 수 있음).
$("[myAttribute='my value']")
당신도 할 수있는
start-with
,
ends-with
,
contains
, 등 ...
.
최신 브라우저는 기본을 지원
querySelectorAll
하므로 다음을 수행 할 수 있습니다.
document.querySelectorAll('[data-foo="value"]');
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
브라우저 호환성에 대한 세부 사항 :
jQuery를 사용하여 더 이상 사용되지 않는 브라우저 (IE9 이상)를 지원할 수 있습니다.
$('[data-foo="value"]');
document.querySelector()
및
document.querySelectorAll()
메소드 를 사용하여 DOM에서 속성 선택기를 사용할 수 있습니다 .당신을 위해 :
document.querySelector("selector[myAttribute='aValue']");
그리고를 사용하여
querySlectorAll()
:
document.querySelectorAll("selector[myAttribute='aValue']");
In
querySelector()
및
querySelectorAll()
Methods "CSS"에서 선택한대로 객체를 선택할 수 있습니다.https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors의 "CSS"속성 선택기에 대한 추가 정보
FindByAttributeValue("Attribute-Name", "Attribute-Value");
ps 정확한 요소 유형을 알고 있다면 세 번째 매개 변수 (예 :)를 추가하십시오
div, a, p ...etc...
.
FindByAttributeValue("Attribute-Name", "Attribute-Value", "div");
그러나 처음에는이 기능을 정의하십시오.
function FindByAttributeValue(attribute, value, element_type) {
element_type = element_type || "*";
var All = document.getElementsByTagName(element_type);
for (var i = 0; i < All.length; i++) {
if (All[i].getAttribute(attribute) == value) { return All[i]; }
}
}
의견 추천에 따라 ps가 업데이트되었습니다.
다음은 src 속성으로 문서에서 이미지를 검색하는 예입니다.
document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");
getAttribute를 사용할 수 있습니다.
var p = document.getElementById("p");
var alignP = p.getAttribute("align");
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
참고 URL :
https://stackoverflow.com/questions/2694640/find-an-element-in-dom-based-on-an-attribute-value
'programing' 카테고리의 다른 글
jQuery에서 문자열이 특정 문자열로 시작 / 종료된다는 것을 아는 방법은 무엇입니까? (0) | 2020.05.08 |
---|---|
둘 이상의 속성으로 find_or_create_by를 가로막습니까? (0) | 2020.05.08 |
부트 스트랩 3 Navbar 접기 (0) | 2020.05.08 |
CSS에서 색상을 변수로 정의하려면 어떻게해야합니까? (0) | 2020.05.07 |
Kotlin 프래그먼트의 뷰에 액세스하려고 할 때 NullPointerException이 발생했습니다. (0) | 2020.05.07 |