DEV Community

Cover image for 🟨 Daily Code 36 | The Document Object Model (DOM)
Gregor Schafroth
Gregor Schafroth

Posted on

🟨 Daily Code 36 | The Document Object Model (DOM)

Hi everyone!

Today I am changing the naming convention of my daily exercises.

So far I counted 🐍 Python (29) and 🟨 JavaScript (6) exercises separately, but starting today I’ll just run a combined counter for all my coding exercises. That’s why I do Daily Code 36 (29 + 6 + 1) today. I’m still putting the programming languages I use in the tags every post, so it should remain easy to see what each of them is about 😊

With that said I’m continuing on my JavaScript journey with the 📺 SuperSimpleDev Tutorial on YouTube

My Code

Wow right at the start of my code I was kind of mind-blown that in document.body.innerHTML the document and body are just objects. Because previously I could never understand the logic of all these many terms that are connected together and suddenly its so logical. 🤦‍♂️ It makes me almost feel stupid that I didn’t notice it before. Here is the code that made it obvious to me:

<!DOCTYPE html>
<head>
    <title>DOM</title>
</head>
<body>
    <button>Hello Earth</button>
    <script>
        // 'document' is the document object (from Document Object Model = 'DOM')
        document.body.innerHTML = 'Hello Mars';
        document.title = 'Hello Venus'
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

it is even more clear with the following code

<!DOCTYPE html>
<head>
    <title>DOM</title>
</head>
<body>
    <button>Hello Earth</button>
    <script>
        console.log(document.title); // this shows DOM (not affected by the next line change)
        document.title = 'Changed (1)'; 
        console.log(document.body.innerHTML); // this shows the whole HTML, including the JS <script> itself!
            console.log(typeof document.body); // jep indeed its an Object
                document.body.innerHTML = 'Changed (2)';
        </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Also not only text, but also code can be inserted

<!DOCTYPE html>
<head>
    <title>DOM</title>
</head>
<body>
    <button>Old button</button>
    <script>
            document.body.innerHTML = '<button>New button</button>';
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

and querySelector() is just a method of the document object to access any element in the HTM!

<body>
    <button>This is a button</button>
    <script>
        console.log(document.querySelector('button').innerHTML)
                document.querySelector('button').innerHTML = 'Changed'
    </script>
</body>
Enter fullscreen mode Exit fullscreen mode

I’m running out of time so that’s it today. Can’t wait to learn more about this tomorrow!!!

Top comments (0)