JavaScript - getElementById() method

revision:


Category : document

The getElementById() method of the Document interface returns an Element object representing the element whose "id property" matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

If you need to get access to an element which doesn't have an ID, you can use querySelector() to find the element using any selector.

The getElementById() method returns an element with a specified value. It returns null if the element does not exist.

Syntax :

        document.getElementById(id)
    

Parameters:

id : required. The ID of the element to locate. The ID is a case-sensitive string which is unique within the document; only one element should have any given ID.

Examples:

            document.getElementById("demo").innerHTML = "Hello World";
        

Practical examples

example: using getElementById() method.

Some text here

code:
                    <div>
                        <p id="para">Some text here</p>
                        <button onclick="changeColor('blue');">blue</button>
                        <button onclick="changeColor('red');">red</button>
                    </div>
                    <script>
                        function changeColor(newColor) {
                            const elem = document.getElementById("para");
                            elem.style.color = newColor;
                        }
                        
                    </script>
                

example: change style of an element.

Thisd is a paragraph

code:
                    <div>
                        <p id="id-1"></p>
                        <p id="id-2">Thisd is a paragraph</p>
                    </div>
                    <script>
                        document.getElementById("id-1").innerHTML = "Hello World";
                        const myElement = document.getElementById("id-2");
                        myElement.style.color = "red";   
                    </script>
                

example: getElementById() method to change paragraph.

A paragraph

Another paragraph

code:
                    <div>
                        <p id="message">A paragraph</p>
                        <p id="id-3"></p>
                        <p id="id-4"></p>
                        <p id="id-5">Another paragraph</p>
                    </div>
                    <script>
                        const p = document.getElementById('message');
                        console.log(p);
                        document.getElementById("id-3").innerHTML =JSON.stringify(p);
                        p.style.color = "blue";
                        p.style.fontWeight ="900";
                        document.getElementById('id-5').style.color = "darkgreen";
                    </script>