最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot set property 'background' of undefined - Stack Overflow

programmeradmin2浏览0评论

When I run the code below, I get the following error:

Uncaught TypeError: Cannot set property 'background' of undefined

What am I doing wrong?

for(var n = 0; n < 5; n++) {
    var heads='head'+n;
    var image="images/"+heads+".jpg";
    console.log(heads);                
    document.getElementsByClassName('horse2').style.background="url("+image+")";
}
#results .horse1 { background-image: url(images/head1.png); }
#results .horse2 { background-image: url(images/head2.png); }
#results .horse3 { background-image: url(images/head3.png); }
#results .horse4 { background-image: url(images/head4.png); }
<table id="results">
    <thead>
    <tr>
        <td>1st</td>
        <td class="horse1"></td>
    </tr>
     <tr>
        <td>1st</td>
        <td class="horse2"></td>
    </tr>
     <tr>
        <td>1st</td>
        <td class="horse3"></td>
    </tr>
    </thead>
</table>

When I run the code below, I get the following error:

Uncaught TypeError: Cannot set property 'background' of undefined

What am I doing wrong?

for(var n = 0; n < 5; n++) {
    var heads='head'+n;
    var image="images/"+heads+".jpg";
    console.log(heads);                
    document.getElementsByClassName('horse2').style.background="url("+image+")";
}
#results .horse1 { background-image: url(images/head1.png); }
#results .horse2 { background-image: url(images/head2.png); }
#results .horse3 { background-image: url(images/head3.png); }
#results .horse4 { background-image: url(images/head4.png); }
<table id="results">
    <thead>
    <tr>
        <td>1st</td>
        <td class="horse1"></td>
    </tr>
     <tr>
        <td>1st</td>
        <td class="horse2"></td>
    </tr>
     <tr>
        <td>1st</td>
        <td class="horse3"></td>
    </tr>
    </thead>
</table>

Share Improve this question edited Jul 21, 2017 at 5:31 user4639281 asked Jul 21, 2017 at 5:10 Shiva KhattriShiva Khattri 131 gold badge1 silver badge7 bronze badges 1
  • Where is your fourth element? – wittich Commented Jul 21, 2017 at 6:25
Add a ment  | 

4 Answers 4

Reset to default 2

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object. The nodes can be accessed by index numbers.

You should use

document.getElementsByClassName('horse2')[0].style.background="url("+image+")";

document.getElementsByClassName('horse2') this will return an array of elements. You should use

document.getElementsByClassName('horse2')[0].style.background="url('img-url')";

You should aware that getElementsByClassName selector returns an array so you need to supply the index for it , change your code to this :

var el = document.getElementsByClassName('horse2')[0];
el.style.background = "url("+image+")";

Document.getElementsByClassName returns an array-like object of all child elements which have all of the given class names.

It is important to note two things:

  1. An array-like object is a regular object with a length property, and properties with sequential numerical names starting at 0. Other than that, it has none of the other methods of a normal array, though it has a couple of its own.
  2. The array-like object returned by Document.getElementsByClassName is a "live HTMLCollection", which means that as elements are added and removed from the DOM, so too will they be added to or removed from the collection.

Document.getElementsByClassName will never return a single element by itself, it will always return a live HTMLCollection.

You have a few options (minor variations may not be mentioned):

  1. Iterate the collection (unnecessary if there will only ever be one element of each class):

    var collection = document.getElementsByClassName('horse2');
    for(var i = 0; i < collection.length; ++i) {
        collection[i].style.background = "url("+image+")";
    }
    
  2. If there will only ever be one element, the remended way would be to use an id instead of a class then use document.getElementById, which returns a reference to a single element with the supplied ID.

    document.getElementById('horse1').style.background = "url("+image+")";
    
  3. If there will only ever be one element and you need to use classes, but you don't need to use Document.getElementsByClassName specifically, you can instead use Document.querySelector, which returns the first Element within the document that matches the specified selector, or group of selectors.

    document.querySelectorAll('.horse1').style.background = "url("+image+")";
    
  4. If there will only ever be one element and you must use Document.getElementsByClassName, you can use bracket notation to select the first element in the collection

    document.getElementsByClassName('horse1')[0].style.background = "url("+image+")";
    

    However, if there ever happens to be no elements in the collection, there will be no first element to select, and you will get the same error all over again.

发布评论

评论列表(0)

  1. 暂无评论