mtwallet
mtwallet

Reputation: 5096

Value from JavaScript object returns null

I am learning JavaScript objects and have set myself a little project to create a slider. Its worth noting I coming from a jQuery background so my problem may lie with the way I trying to select the elements. I have the following HTML:

<div class="slider-viewport" id="mySlider">
    <div class="slides-container">
        <div class="slide">1</div>

        <div class="slide">2</div>

        <div class="slide">3</div>
    </div>
</div>

and the following JavaScript:

(function(window, document, undefined){

    // code that should be taken care of right away

    window.onload = init;

    function init(){
        // the code to be called when the dom has loaded

        var slider = {
            sliderViewport: document.getElementById('mySlider'),
            slidesContainer: document.querySelectorAll(this.sliderViewport + ' .slides-container')
        };

        console.dir(slider.sliderViewport + ' .slides-container');
        console.dir(slider.slidesContainer);

        //Just testing to see if I can do something
        slider.slidesContainer.style.color = 'blue';
    }

})(window, document, undefined);

When I view Chrome Dev Tools I get the following:

[object HTMLDivElement] .slides-container
objects.js:16 NodeList[0]
objects.js:18 Uncaught TypeError: Cannot set property 'color' of undefined

The first console.dir seems to return the element I am after. I'm not sure what the second console.dir is returning and also why I get an error of undefined. Please can you give me a steer on where I am going wrong?

Many thanks in advance.

Upvotes: 0

Views: 133

Answers (2)

DontVoteMeDown
DontVoteMeDown

Reputation: 21475

querySelectorAll() expects a string as parameter to evaluate as a CSS selector. You can't concat a HtmlDivElement with a string, this is your first problem. The second one is that the querySelectorAll() returns a NodeList as you can see on the console. The problem is that the list is empty.

You may want to try this:

var slider = {
    sliderViewport: document.getElementById('mySlider')
}

slider.slidesContainer: slider.sliderViewport.querySelectorAll('.slides-container');

I didn't tested it, but it should works as described here.

Upvotes: 1

Kirill Pisarev
Kirill Pisarev

Reputation: 843

querySelectorAll and querySelector gets a string parameter (css selector):

var slider = {
            sliderViewport: document.querySelector('#mySlider'),
            slidesContainer: document.querySelector('#mySlider .slides-container')
        };

Upvotes: 1

Related Questions