[英]Search DOM for special html tags without JQuery
I am working on make a project that requires looking for special tags on a page and then getting its attributes. 我正在做一个需要在页面上查找特殊标签然后获取其属性的项目。 An example of the tag looks something like this:
标签的示例如下所示:
<ub:widget tag1="abc" tag2="doeraeme"></ub:widget:>
WITHOUT JQuery , how can I using Javascript search for each ub:widget and then collect their attributes individually? 没有JQuery ,如何使用Javascript搜索每个ub:widget,然后分别收集其属性?
Use getElementsByTagName
then getAttribute
: 使用
getElementsByTagName
然后使用getAttribute
:
window.onload = function() {
var elements = document.getElementsByTagName("ub:widget");
for (var i = 0; i < elements.length; i++) {
var widget = elements[i];
var tag1 = widget.getAttribute("tag1");
var tag2 = widget.getAttribute("tag2");
alert("Found a widget! tag1 is " + tag1 + " and tag2 is " + tag2);
}
}
Live test case . 现场测试用例 。
If you need it more generic ie don't have predefined tag name you can iterate all elements and look for those containing ":" in the tag name which usually means "special tag": 如果您需要更通用的名称,即没有预定义的标签名称,则可以迭代所有元素,并在标签名称中查找包含“:”的元素,这通常意味着“特殊标签”:
window.onload = function() {
var elements = document.getElementsByTagName("*");
for (var i = 0; i < elements.length; i++) {
var curElement = elements[i];
var curTagName = curElement.tagName.toLowerCase();
if (curTagName.indexOf(":") > 0) {
var widget = curElement;
var message = "Found a widget! Tag name is: " + curTagName;
if (widget.attributes.length === 0) {
message += " without any attributes";
} else {
message += " with " + widget.attributes.length + " attributes: ";
for (var j = 0; j < widget.attributes.length; j++) {
var curAttribute = widget.attributes[j];
message += "\n" + curAttribute.name + " = " + curAttribute.value;
}
}
alert(message);
}
}
}
Updated fiddle with the generic approach. 用通用方法更新了小提琴 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.