programing

속성 값을 기반으로 DOM에서 요소 찾기

new-time 2020. 5. 8. 23:08
반응형

속성 값을 기반으로 DOM에서 요소 찾기


주어진 속성 이름과 속성 값을 가진 요소를 검색하는 DOM API가 있는지 알려주세요.다음과 같은 것 :

doc.findElementByAttribute("myAttribute", "aValue");

업데이트 :

지난 몇 년 동안 풍경이 크게 바뀌 었습니다. 이제 안정적으로 사용할 수 있습니다

querySelector

querySelectorAll

참조

보이 테크의 대답

이 작업을 수행하는 방법에 대한합니다.이제 jQuery 종속성이 필요하지 않습니다. jQuery를 사용하는 경우 훌륭합니다 ... 사용하지 않으면 더 이상 속성별로 요소를 선택하는 데 의존 할 필요가 없습니다.


바닐라 자바 ​​스크립트 에서이 작업을 수행하는 매우 짧은 방법은 없지만 몇 가지 솔루션이 있습니다.

요소를 반복하고 속성을 확인하여 이와 같은 작업을 수행합니다.

 

jQuery

와 같은 라이브러리 가 옵션 이라면 다음과 같이 조금 더 쉽게 할 수 있습니다.

$("[myAttribute=value]")

값이 유효한

CSS 식별자

가 아닌 경우 (공백 또는 문장 부호 등) 값 주위에 따옴표가 필요합니다 (단일 또는 이중 일 수 있음).

$("[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

반응형