I am making an <anchor>
element which is meant to clone the <a>
element. I have two of the <anchor>
elements in my body but only one has been converted to an <a>
element! Here is my JavaScript:
var t = document.getElementsByTagName("anchor");
for (var i = 0; i < t.length; i ) {
var c = t[i];
var a = document.createElement("a");
a.setAttribute("href", c.getAttribute("href") "?utm_source=" window.location.href);
a.innerHTML = c.innerHTML;
c.parentElement.append(a);
c.remove();
}
CodePudding user response:
getElementsByTagName()
is a live HTMLCollection, so when you call c.remove()
, the length of t
becomes 1. You can circumvent this by caching t.length
:
var tLen = t.length;
for (v i = 0; i < tLen; i ) {
CodePudding user response:
It looks like you are trying to use .length to loop though an object, when .length only works on arrays.
getElementsByTagName() returns a object, not an array and Array.prototype.length only works on arrays.
I found a other post about getting an array of getElementsByTagName(): Link