Reputation: 2675
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
Upvotes: 8
Views: 107063
Reputation: 519
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.
Upvotes: 12
Reputation: 31
If you should use querySelectorAll
the answer of @Viktor Akanam will help you
Or you can just sue querySelector
instead of querySelectorAll
!
Upvotes: 1
Reputation: 21
If you assign the variable using any selector capable of selecting more than one element at a time (eg. getElementsByClassName
, querySelectorAll
) then it shows the error so use any selector that select single element at a time (Eg: getElementById
)
Upvotes: 2
Reputation: 31
when using querySelectorAll(), treat this as an array, you need a 'for loop' to step through the different elements. eg.
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.
Upvotes: 3
Reputation: 631
try this:
var link = "http://www.someurl.com";
var preview = document.querySelectorAll ("#preview");
preview[0].setAttribute("data", link);
Upvotes: 0