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. Through this tutorial. you will learn how to get HTML elements id, name, tag, class, attribute, value using getElementById(), getElementsByClassName(), getElementByName(), getElementsByTagName() in JavaScript.

Through this tutoiral, you can easily select dom element and it’s value by it’s id, name, class, tag, and attribute in JavaScript uisng js built in methods getElementById(), getElementsByClassName(), getElementByName(), getElementsByTagName() in JavaScript.

JavaScript Select Element By id, Class, Tag, Name, Attribute

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

  • JavaScript Get Element By Id Value
  • JavaScript Get Element By Class Name
  • JavaScript Get Element By Name
  • JavaScript Get Element By Tag Name
  • JavaScript Get Element By Attribute Name

JavaScript Get Element By Id Value

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.

JavaScript Get Element By Class Name

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"]

JavaScript Get Element By Name

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.

JavaScript Get Element By Tag Name

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>

JavaScript Get Element By Attribute Name

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

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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