JavaScript Get Element By id, name, class, tag value

JavaScript Get Element By id, name, class, tag value

Javascript access the dom elements by id, class, name, tag, attribute and it’s valued. Here you will learn how to get HTML elements values, attributes by getElementById(), getElementsByClassName(), getElementByName(), getElementsByTagName().

Selecting Elements in Document

The following javascript dom method help to select the elements in document.

1: JavaScript getElementById() method

The JavaScript getElementById() is a dom method to allows you to select an element by its id.

The following syntax represents the getElementById() method:

let element = document.getElementById(id);

Note that, the id is case-sensitive. For example, the 'myId' and 'MyId' are totally different ids.

This method returns an Element object that describes the DOM element object with the specified id or null in case no matching element found.

The id also unique in the dom. If more than one element with the same id in dom, it returns only the first one it encounters.

JavaScript getElementById() method Example

Consider the following HTML document:

<html>
<head>
<title>JavaScript get Element by id Example</title>
</head>

<body>
<input id='my_id' value="Hello This is test">
<button onclick="getElementBy();">getElementById</button>
<script type="text/javascript">

function getElementBy()
{
 elem = document.getElementById('my_id').value;
 alert(elem);
}
</script>
</body>
</html>

The document contains a input element that has the id attribute with the value the my_id.

2: JavaScript getElementsByClassName() method

The JavaScript getElementByClassName() is a dom method to allows you to select an element by its class name.

The following syntax represents the getElementByClassName() method:

let elements = document.getElementsByClassName(classNames)
let elements = parentElement.getElementsByClassName(classNames)

In this syntax, the classNames parameter is a string that represents a class name or a list of comma-separated class names to match.

JavaScript getElementsByClassName() example

Suppose that you have the following HTML:

<html>
<head>
<title>JavaScript get Element by class name Example</title>
</head>
<div id="app">
    <header>
        <nav>
            <ul id="menu">
                <li class="item">HTML</li>
                <li class="item">CSS</li>
                <li class="item highlight">JavaScript</li>
                <li class="item">TypeScript</li>
            </ul>
        </nav>
        <h1>getElementsByClassName Demo</h1>
    </header>
     <section>
        <article>
            <h2 class="heading-secondary">Example 1</h2>
        </article>
        <article>
            <h2 class="heading-secondary">Example 2</h2>
        </article>
    </section>
</div>
</body>
</html>

Calling JavaScript getElementsByClassName() methods on dom element.

The following example represents how to use the getElementsByClassName() method to select the <li> item which are the descendants of the <ul> element:

let menu = document.getElementById('#menu');
let items = menu.getElementsByClassName('item');

let data = [].map.call(items, item => item.textContent);

console.log(data);

Output:

["HTML", "CSS", "JavaScript", "TypeScript"]

3: JavaScript getElementsByName() method

The JavaScript getElementByName() is a dom method to allows you to select an element by its name.

The following syntax to represents the getElementsByName() method:

let elements = document.getElementsByName(name);

The getElementsByName() accepts a name which is the value of the name attribute of elements and returns it value.

JavaScript getElementsByName() example

The following example shows a list of radio buttons that have the same name (rate).

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JavaScript getElementsByName Demo</title>
</head>
<body>
    <p>Please rate the service:</p>
    <p>
        <input type="radio" name="rate" value="Very poor"> Very poor
        <input type="radio" name="rate" value="Poor"> Poor
        <input type="radio" name="rate" value="OK"> OK
        <input type="radio" name="rate" value="Good"> Good
        <input type="radio" name="rate" value="Very Good"> Very Good
    </p>
    <p>
        <button id="btnRate">Submit</button>
    </p>
    <script>
        let btn = document.getElementById('btnRate');

        btn.addEventListener('click', () => {
            let rates = document.getElementsByName('rate');
            rates.forEach((rate) => {
                if (rate.checked) {
                    alert(`You rated: ${rate.value}`);
                }
            })
        });
    </script>
</body>
</html>

When you click the Rate button, the page will show an alert dialog that displays the your selected radio button value.

4: JavaScript getElementByTagName method

The JavaScript getElementsByTagName() is a dom method to allows you to select an element by its tag name.

The following syntax represents the getElementsByTagName() method:

let elements = document.getElementsByTagName(tagName);

JavaScript getElementByTagName example

The following example illustrates how to use the getElementsByTagName() method to get the number of H2 tags in the document.

When you click the Count H2 button, the page shows the number of H2 tags

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript getElementsByTagName() Demo</title>
</head>
<body>
    <h1>JavaScript getElementsByTagName() Demo</h1>
    <h2>First heading</h2>
    <p>This is the first paragraph.</p>
    <h2>Second heading</h2>
    <p>This is the second paragraph.</p>
    <h2>Third heading</h2>
    <p>This is the third paragraph.</p>

    <button id="btnCount">Count H2</button>

    <script>
        let btn = document.getElementById('btnCount');
        btn.addEventListener('click', () => {
            let headings = document.getElementsByTagName('h2');
            alert(`The number of H2 tags: ${headings.length}`);
        });
    </script>
</body>

</html>

5: JavaScript Get Element by Attribute

Use JavaScript getElementsByTagName() with getAttribute() method to allow select an element by its tag name and attribute.

The following syntax represents the attribute() method:

elem = document.getElementsByTagName("input")[0].getAttribute("class");

JavaScript get Element by Attribute Example

The following example illustrates how to use the getElementsByTagName() with getAttribute() method to get the class of input tags in the document.

<html>
<head>
<title>JavaScript get Element by Attribute Example</title>
</head>

<body>
<input class="my_class" value="Hello This is test">
<button onclick="myFunc();">getElementsByAttribute</button>
<script type="text/javascript">

function myFunc()
{
 elem = document.getElementsByTagName("input")[0].getAttribute("class");
 alert(elem);
}
</script>
</body>
</html>

Recommended JavaScript Tutorial

  1. JavaScript Create & Call Functions with Example
  2. JavaScript Operators With Examples
  3. String Contains JavaScript | String includes() Method
  4. JavaScript Replace String With Examples
  5. JavaScript Array splice() Method By Example
  6. JavaScript: Clone an Array & Object By Examples
  7. Sorting Using JavaScript Array Sort() Method
  8. JavaScript: Convert String to Array JavaScript
  9. javaScript Push() Array By Example
  10. javaScript Push Array, Items Into Array Example
  11. Check the Object is Array or not in javascript
  12. JavaScript: Important Array Methods
  13. Highlight Search Result Vanilla JavaScript

AuthorTuts Make

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Codeigniter, Vue JS, Angular JS, React Js, WordPress and Bootstrap from a starting stage.

Leave a Reply

Your email address will not be published. Required fields are marked *