Random guy
Random guy

Reputation: 923

How is .toggle() function being called when using javascript?

I am learning javascript and I have a box and i want to change its class name. So,

var el=document.querySelectorAll('.myClass');

        for(var x=0;x<el.length;x++){
            el[x].onclick=function(){
               // this.classList.toggle(box1); how is this.classList.toggle possible here? I am not seeing it when doing console.dir(this.classList)
                console.dir(this.classList);
            }
        }
<style>
        .box1{
            background-color: aqua;
            font-size: 1.5em;
            color: #fff;
        }

        .box2{
            background-color: red;
            font-size: 0.5em;
            color: #ddd;
        }

        #one,#two,#three{
            width: 100px;
            height: 100px;
            display: inline-block;
            border: 1px solid black;
        }
    </style>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    
</head>
<body>
    <div id="one" class="myClass">Box 1</div>
    <div id="two" class="myClass">Box 2</div>
    <div id="three" class="myClass">Box 3</div>
   
</body>
</html>

When I click the box I am getting the current object in console.log(this);. I saw the classList property. So I am fine upto console.dir(this.classList);.But,my tutor is using this.classList.toggle(box1);.I didnt understand how he is getting option to call .toggle() function there? When i looked at

 `console.log(this.classList);` 

I saw only

 DOMTokenList ["myClass", value: "myClass"]
    0: "myClass"
    length: 1
    value: "myClass"
    __proto__: DOMTokenList

But i didnt see any option of .toggle() there? But how can we know that toggle can be used after this.classList since I am not seeing any property of toggle() function after this.classList? Please clarify me.

Upvotes: 0

Views: 51

Answers (2)

Kalimah
Kalimah

Reputation: 11437

From MDN website:

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.

Therefore to find what properties (functions, setters, getters .. etc) exist you can view them under __proto__.

Upvotes: 1

Quentin
Quentin

Reputation: 944196

console.log only logs enumerable properties. toggle isn't enumerable.

console.log("toggle" in document.body.classList);
console.log(document.body.classList.propertyIsEnumerable("toggle"));

Upvotes: 0

Related Questions