특성 값을 기준으로 DOM에서 요소 찾기
주어진 속성 이름과 속성 값을 가진 요소를 검색하는 DOM API가 있는지 알려주실 수 있나요?
예를 들어 다음과 같습니다.
doc.findElementByAttribute("myAttribute", "aValue");
최신 브라우저는 네이티브 지원querySelectorAll
다음 작업을 수행할 수 있습니다.
document.querySelectorAll('[data-foo="value"]');
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
브라우저 호환성 세부 정보:
jQuery를 사용하여 오래된 브라우저(IE9 이전 버전)를 지원할 수 있습니다.
$('[data-foo="value"]');
최신 정보: 지난 몇 년간 풍경이 크게 변화했습니다.이제 확실하게 사용할 수 있습니다.querySelector
그리고.querySelectorAll
자세한 내용은 Wojtek의 답변을 참조하십시오.
이제 jQuery 종속성은 필요 없습니다.jQuery를 사용하고 있다면, 좋습니다.그렇지 않다면 더 이상 속성에 따른 요소 선택에만 의존할 필요가 없습니다.
vanilla javascript에서는 간단한 방법은 없지만 몇 가지 솔루션이 있습니다.
요소를 루프하고 속성을 확인하는 것과 같은 작업을 수행합니다.
jQuery와 같은 라이브러리가 옵션인 경우 다음과 같이 좀 더 쉽게 수행할 수 있습니다.
$("[myAttribute=value]")
값이 유효한 CSS 식별자(스페이스나 구두점 등)가 아닌 경우 값 주위에 따옴표가 필요합니다(단일 또는 이중일 수 있습니다).
$("[myAttribute='my value']")
할 수도 있습니다.start-with
,ends-with
,contains
등...아트리뷰트 셀렉터에는 몇 가지 옵션이 있습니다.
DOM의 Atribute Selector를 사용하여document.querySelector()
그리고.document.querySelectorAll()
방법들.
고객님의 경우:
document.querySelector("[myAttribute='aValue']");
를 사용하여querySelectorAll()
:
document.querySelectorAll("[myAttribute='aValue']");
인querySelector()
그리고.querySelectorAll()
"CSS"에서 선택한 오브젝트를 선택할 수 있습니다.
https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors에서 "CSS" 속성 선택기에 대한 자세한 내용을 참조하십시오.
FindByAttributeValue("Attribute-Name", "Attribute-Value");
p.s. 정확한 요소 유형을 알고 있는 경우 세 번째 매개 변수(즉,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]; }
}
}
코멘트 권장 사항에 따라 갱신된 p.s.
쿼리 실렉터를 사용합니다.예:
document.querySelectorAll(' input[name], [id|=view], [class~=button] ')
input[name]
요소 입력name
소유물.
[id|=view]
다음 문자로 시작하는 ID를 가진 요소view-
.
[class~=button]
의 요소button
학급.
getAttribute를 사용할 수 있습니다.
var p = document.getElementById("p");
var alignP = p.getAttribute("align");
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
다음으로 문서 내의 이미지를 src 속성으로 검색하는 예를 나타냅니다.
document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");
다음을 사용하여 선택할 수 있습니다.querySelector
:
document.querySelector("tagName[attributeName='attributeValue']")
다니엘 데 레온의 답변 수정안
색할할수수수 it it it it it it with with with로 할 수 있어요.
^=
- 기타 가 - id(으)로 view
(키워드)
document.querySelectorAll("[id^='view']")
function optCount(tagId, tagName, attr, attrval) {
inputs = document.getElementById(tagId).getElementsByTagName(tagName);
if (inputs) {
var reqInputs = [];
inputsCount = inputs.length;
for (i = 0; i < inputsCount; i++) {
atts = inputs[i].attributes;
var attsCount = atts.length;
for (j = 0; j < attsCount; j++) {
if (atts[j].nodeName == attr && atts[j].nodeValue == attrval) {
reqInputs.push(atts[j].nodeName);
}
}
}
}
else {
alert("no such specified tags present");
}
return reqInputs.length;
}//optcount function closed
이것은 특정 속성값을 가진 특정 태그를 선택하기 위해 사용되는 함수입니다.전달되는 파라미터는 태그 ID, 그 태그 ID 내의 태그 이름, 속성 및 네 번째 속성 값입니다.이 함수는 지정된 특성 및 값을 사용하여 발견된 요소의 수를 반환합니다.고객님의 필요에 따라 수정할 수 있습니다.
언급URL : https://stackoverflow.com/questions/2694640/find-an-element-in-dom-based-on-an-attribute-value
'sourcecode' 카테고리의 다른 글
MySql/MariaDB는 Debian 9.1 서버의 기본 데이터 주소를 변경할 수 없습니다. (0) | 2023.01.20 |
---|---|
Python의 for loop에 continue와 pass in의 차이가 있습니까? (0) | 2023.01.20 |
시스템 간의 차이.getenv() 및 System.getProperty() (0) | 2023.01.20 |
IntelliJ IDEA에서 "Error:java: Compilation failed: internal Java compiler error idea"라고 표시됨 (0) | 2023.01.20 |
Composer 업데이트 메모리 제한 (0) | 2023.01.20 |