我的具体情况是,我试图从DOM中删除/使inactive成为一个链接元素(我无法控制它的生成)。我计划这样做的方式是用一个无意义的值替换'href‘属性--我之所以选择这样做而不是简单地使用disable = true,是为了在其他情况下可以重用该函数来更改其他属性。
我遇到的问题是.getAttribute返回错误"TypeError: elemArr.hasAttribute不是函数“。
function removeLink(elem, att, value, replacement) {
var elemArr = document.getElementsByTagName(elem);
for (var i = 0; i < elemArr.length; i++) {
var workingAtt = elemArr.hasAttribute(att);
if (workingAtt.value === filePath) {
elemArr[i].setAttribute(att, replacement);
}
}
}
removeLink("link", "href", "filePath", "#");对于为什么要抛出此错误的任何帮助都是非常感谢的。
发布于 2015-06-08 16:02:52
elemArr是一个数组,而数组没有hasAttribute方法。将代码重写为
function removeLink(elem, att, value, replacement) {
var elemArr = document.getElementsByTagName(elem);
for (var i = 0; i < elemArr.length; i++) {
//this line here wasn't referring to a specific node but the array
var workingAtt = elemArr[i].hasAttribute(att);
if (workingAtt && elemArr[i].getAttribute(att) === value) {
elemArr[i].setAttribute(att, replacement);
}
}
}
removeLink("link", "href", "filePath", "#");它会成功的。
一种更简单的方法是这样的:
function removeLink(elem, att, value, replacement){
var selector = elem + '['+ att +'="'+ value +'"]';
[].forEach.call(document.querySelectorAll(selector), function(node){
node.setAttribute(att, replacement);
});
}它做的基本上是一样的事情,但更短一些,更明确。
发布于 2015-06-08 16:00:48
.hasAttribute()返回布尔值true或false。因此,workingAtt要么等于true,要么等于false。布尔值不是HTMLElements,因此它们没有value属性。这就是为什么会有错误。
看起来你在尝试做一些类似select elements where there is a href attribute的事情。
如果是这样,您只需过滤它们:
var myElements = [];
[].filter.call(elemArr, function(el) {
if(el.hasAttribute(att)) {
myElements.push(el);
}
});
// then, do something with myElements发布于 2015-06-08 16:07:47
您的代码中有几个错误:
elemArr.hasAttribute而不是elemArr[i].hasAttribute。var workingAtt = elemArr.hasAttribute(att); -在这里,workingAtt是一个布尔值,workingAtt.value是不存在的.您应该使用elemArr[i].getAttribute(att),然后使用workingAtt,而不是workingAtt.value (它将不再存在!)if (workingAtt.value === filePath)与filePath相比较,而最确切的是应该将其与传递给函数的value进行比较。https://stackoverflow.com/questions/30713903
复制相似问题