I am trying to modify a webpage with a chrome plugin I wrote myself. I'd like to add an additional link before a existing link.
I am using insertAdjacentHTML to add my new link before the original link. But as soon as I use the a href it fails.
UPDATE There were syntax errors in my code as many pointed out. I fixed these
This is the new code (but still won't work...webpage I want to alter seems to load forever and nothing happens):
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].href = "javascript:void(0)";
anchors[i].insertAdjacentHTML("beforebegin", "<a href='www.google.de'> bold text</a>")
}
Somehow the whole code works, if I don't add "a href". So this works:
anchors[i].insertAdjacentHTML("beforebegin", "<b> bold text</b>")
If I try the tag ..it somehow fails - can you give me a hint why?
Update2 I was finally able to solve this: I accidentally create an infinite loop. @Andy's answer points out a solutions to this.
答案 0 :(得分:2)
除了拼写错误外,代码的主要问题是getElementsByName
返回了锚点的实时列表。在适当的情况下这可能很有用,但是在您的循环中,您每次迭代都会向列表中添加一个 new锚点,因此循环永远无法完成并且浏览器会挂起。为防止这种情况,请使用querySelectorAll
。而是返回 static 列表。
var anchors = document.querySelectorAll('a');
for (var i = 0; i < anchors.length; i++) {
const newAnchor = '<a href="www.google.de">bold text</a>';
anchors[i] = 'javascript:void(0)';
anchors[i].insertAdjacentHTML('beforebegin', newAnchor);
}
<a href="www.google.com">Google</a>
<a href="www.bert.com">Bert</a>
<a href="www.ernie.com">Ernie</a>
从长远来看,如果您打算使用JS和HTML进行大量编码,则可能会发现始终对JS字符串等使用单引号,对HTML属性使用双引号会更容易。这样,您必须转义引号的次数将受到限制。
您还会发现使用像VSCode这样的体面的代码编辑器,可以帮助您在输入错误之前将其输入浏览器。
答案 1 :(得分:1)
您在设置href时遇到错字:
anchors[i].href = "javascript:void(0)
您已经在此处打开了一个字符串,但没有将其关闭。只需在末尾添加"
。
使用带有适当语法突出显示功能的文本编辑器可以帮助避免此类问题(尽管JS语法突出显示对于此特定问题通常有点奇怪)。
如果您在浏览器开发人员工具中查看过控制台,您也会看到一个错误(对于大多数浏览器,通过按F12
打开这些控制台)。
答案 2 :(得分:0)
检查您的代码,缺少"
和;
。
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].href = "javascript:void(0)";
anchors[i].insertAdjacentHTML("beforebegin", "<a href='www.google.de'> bold text</a>")
}