How To Use HTML DOM GetElementById Method In JavaScript

admin_img Posted By Bajarangi soft , Posted On 29-09-2020

In Java script we can change text or text color using id of html tags today we are going to discuss how to get element by id in java script

How To Use HTML DOM GetElementById Method In JavaScript

The getElementById() method returns the element that has the ID attribute with the specified value.

This method is one of the most common methods in the HTML DOM, and is used almost every time you want to manipulate, or get info from, an element on your document.

Returns null if no elements with the specified ID exists.

An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element in the source code.

Syntax and Usage

document.getElementById(elementID)
 

Parameter Values

elementID   String Required. The ID attribute's value of the element you want to get


Example(1)
<h1 id="demo">Hello World</h1>
<button class="btn btn-primary" onclick="change_id()">Click it</button>
<script>
    function change_id() {
        document.getElementById("demo").innerHTML = "Hello World ! Welcome to Bajarangisoft";
    }
</script>

In above example change the specified paragraph after on click of button 

Example(2)
<p id="demo">Click the button to change the color of this paragraph.</p>

<button onclick="change_text_color()">Try it</button>

<script>
    function change_text_color() {
        var x = document.getElementById("demo");
        x.style.color = "red";
    }
</script>

In above example change the specified paragraph color after on click of button 

Complete Code For GetElementById Method In JavaScript
<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM GetElementById Method In JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <br>
    <br>
    <div class="text-center">
        <h1>HTML DOM GetElementById Method In JavaScript</h1>
    </div>
    <br>
    <div class="well">
        Click the button to change the text in this paragraph.
        <h1 id="demo">Hello World</h1>
        <button class="btn btn-primary" onclick="change_id()">Click it</button>
    </div>
    <br>
</div>
</body>
</html>
<script>
    function change_id() {
        document.getElementById("demo").innerHTML = "Hello World ! Welcome to Bajarangisoft";
    }
</script>

 

Related Post