CodeGym/Java Course/Module 3. Java Professional/Working with the Document Object Model (DOM)

Working with the Document Object Model (DOM)

Available

5.1 document.getElementById()

As you know, JavaScript was created to add some animation to HTML pages. So far, we haven't said much about it. How to add this same animation? How, for example, to change the color of an element?

To change the color of an element, you first need to find this element. To do this, there is a function document.getElementById();You write in your HTML idat the desired element, and then access it from JavaScript. Example:

<head>
    <script>
        function changeImage()
        {
           var image = document.getElementById("image123");
            image.src = "new-image.png";
        }
    </script>
</head>
<body>
    <img id="image123" scr="big-image.png" onclick="changeImage()">
</body>

After the user clicks on the image, the function is called changeImge(). Inside it, we get the element imageby its ID, and then change the value of its src attribute to a new one. Which will cause the element imgto load a new image.

5.2 document.createElement()

In addition to getting an element, we can also create new elements and delete existing ones.

Creating elements is very easy. To do this, you need to do two things: a) create an element , b) add it to the right place in the document. It usually looks like this:

<head>
    <script>
        window.onload = function ()   {
            var image = document.createElement("IMG");
            var image.src = "big-image.png";
            document.body.addAfter(image);
        }
    </script>
</head>
<body>
</body>

5.3 window.navigate() method

Another very useful method is the window.navigate(). With it, you can force the browser to load a new page instead of the current one. Just pass it URLto this method and call it. Example:

<body>
  <img scr="big-image.png" onclick="window.navigate('https://google.com');">
</body>

In the example above, after the user clicks on the image, the page google.com will be loaded into the current tab.

5.4 Current URL

And one more useful thing. Sometimes a script needs to know the current page URL. For example, the same script can be added to different pages. How to do it?

There is a special property for this.document.location.href

var currentURL = document.location.href;
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet