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
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.