'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
Solution 1:[1]
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.
Solution 2:[2]
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)
Solution 3:[3]
If you should use querySelectorAll the answer of @Viktor Akanam will help you
Or you can just sue querySelector instead of querySelectorAll!
Solution 4:[4]
try this:
var link = "http://www.someurl.com";
var preview = document.querySelectorAll ("#preview");
preview[0].setAttribute("data", link);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Victor Akanam |
| Solution 2 | Rifky Niyas |
| Solution 3 | Rifky Niyas |
| Solution 4 | Alexandr Kudryashov |
