Javascript element.setAttribute 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35626658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:02:07  来源:igfitidea点击:

element.setAttribute is not a function

javascriptobjectsetattribute

提问by Lazarus Rising

So, i know that this has already been answered, but none of the previous answers managed to make my code work. I have a html structure as the following:

所以,我知道这已经得到了回答,但是以前的答案都没有使我的代码工作。我有一个 html 结构如下:

<div class="form">
    <div class="formrow">
        <div class="previewcontainer">
            <object id="preview">
            <object>
        </div>
    </div>
</div>

I am trying to set the data attribute to the object like this:

我正在尝试将数据属性设置为这样的对象:

var link = "http://www.someurl.com";
var preview = document.querySelectorAll ("#preview");
preview.setAttribute("data", link);

However, I get an error preview.setAttribute is not a function

但是,我收到一个错误 preview.setAttribute is not a function

回答by Maanus Indov

or this:

或这个:

var link = "http://www.someurl.com";
var preview = document.getElementById("preview"); //getElementById instead of querySelectorAll
preview.setAttribute("data", link);

Be sure to run the code after the element is created, or use jQuery code:

确保在创建元素后运行代码,或者使用 jQuery 代码:

$( document ).ready(function() {
}

"Uncaught TypeError: Cannot read property 'setAttribute' of null"

“未捕获的类型错误:无法读取 null 的属性‘setAttribute’”

By: LazarusRising—in that case, the element doesn't exist yet in the document. You need to run the code after the element is created, say after the load event or a script below the element.

作者:LazarusRising——在这种情况下,文档中还不存在该元素。您需要在创建元素后运行代码,例如在加载事件或元素下方的脚本之后。

回答by Victor Akanam

when using querySelectorAll(), treat this as an array, you need a 'for loop' to step through the different elements. eg.

使用 querySelectorAll() 时,将其视为数组,您需要一个“for 循环”来遍历不同的元素。例如。

var link = "http://www.someurl.com";
var preview = document.querySelectorAll ("#preview");
for (var i = 0; i < preview.length;  i++ {
preview[i].setAttribute("type", 'href');
}

This will now change the 'type attributes' of all the elements with an id of 'preview' to a link.

现在,这会将所有具有“预览”ID 的元素的“类型属性”更改为链接。

回答by Alexandr Kudryashov

try this:

尝试这个:

var link = "http://www.someurl.com";
var preview = document.querySelectorAll ("#preview");
preview[0].setAttribute("data", link);