element.setAttribute不是函数

问题描述 投票:1回答:2

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

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

我试图将data属性设置为对象,如下所示:

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

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

javascript object setattribute
2个回答
3
投票

或这个:

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

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

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

“未捕获的TypeError:无法读取null的属性'setAttribute'”

通过:LazarusRising-在这种情况下,元素在文档中尚不存在。您需要在创建元素后运行代码,例如在load事件之后或元素下面的脚本。


0
投票

试试这个:

var link = "http://www.someurl.com";
var preview = document.querySelectorAll ("#preview");
preview[0].setAttribute("data", link);
© www.soinside.com 2019 - 2024. All rights reserved.