你能告诉我是否有任何DOM API可以搜索给定属性名和属性值的元素吗?
喜欢的东西:
doc.findElementByAttribute("myAttribute", "aValue");
你能告诉我是否有任何DOM API可以搜索给定属性名和属性值的元素吗?
喜欢的东西:
doc.findElementByAttribute("myAttribute", "aValue");
当前回答
下面是一个例子,如何通过src属性在文档中搜索图像:
document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");
其他回答
我们可以通过使用document.querySelector()和document.querySelectorAll()方法在DOM中使用属性选择器。
你的:
document.querySelector("[myAttribute='aValue']");
使用querySelectorAll():
document.querySelectorAll("[myAttribute='aValue']");
在querySelector()和querySelectorAll()方法中,我们可以像在“CSS”中一样选择对象。
关于“CSS”属性选择器的更多信息,请参见https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
很简单,试试这个
<!DOCTYPE html>
<html>
<body>
<h1>The Document Object</h1>
<h2>The querySelector() Method</h2>
<h3>Add a background color to the first p element:</h3>
<p>This is a p element.</p>
<p data-vid="1">This is a p element.</p>
<p data-vid="2">This is a p element.</p>
<p data-vid="3">This is a p element.</p>
<script>
document.querySelector("p[data-vid='1']").style.backgroundColor = "red";
document.querySelector("p[data-vid='2']").style.backgroundColor = "pink";
document.querySelector("p[data-vid='3']").style.backgroundColor = "blue";
</script>
</body>
</html>
下面是如何使用querySelector进行选择:
document.querySelector("tagName[attributeName='attributeValue']")
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内的标签名),属性,第四个是属性值。 此函数将返回指定属性中找到的元素数量及其值。 你可以根据自己的需要修改。
下面是一个例子,如何通过src属性在文档中搜索图像:
document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");