Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element.setAttribute is not a function

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:

<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

like image 641
Lazarus Rising Avatar asked Jun 11 '26 04:06

Lazarus Rising


1 Answers

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:

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


    

@Lazarus Rising mentioned,

Uncaught TypeError: Cannot read property 'setAttribute' of null

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.

like image 63
inubs Avatar answered Jun 13 '26 07:06

inubs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!