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)