Loading...
Home Picture
Code

GetElementById Javascript DOM Method

Scroll Down

The javascript Document method getElementById(String) is a fast way of returning an HTML Element Object representing the element that matches the specified idstring parameter.

Quick Usage

var element = getElementById("html-tag-id-attribute");

Method Details

  • Syntax

    var element = getElementById(id);

  • Paramenter

    The id parameter is a string with the html element id attribute to be searched.

  • Return Value

    HTML Element Object or NULL.

  • Support

    All browsers.

  • More References

Performance Comparison

Consider the following HTML setup. The goal of this test is to select the section‘s first div element

<section>
<div class="class-selector-0 general" id="id-selector-0"></div>
<div class="class-selector-1 general" id="id-selector-1"></div>
<div class="class-selector-2 general" id="id-selector-2"></div>
</section>

  • DOM getElementById( ) – 386.44 – FASTEST

    var element = document.getElementById("id-selector-0");

  • DOM getElementsByClassName( ) – 141.60

    var element = document.getElementsByClassName("class-selector-0")[0];

  • DOM querySelector( ) by id – 140.65

    var element = document.querySelector('#id-selector-0');

  • DOM getElementsByTagName( ) – 139.91

    var element = document.getElementsByTagName("div")[0];

  • jQuery( ) id selector – 24.52

    var element = $("#id-selector-0").get(0);

  • jQuery( ) class selector – 8.94

    var element = $("#id-selector-0").get(0);

  • DOM querySelector( ) by class name – 2.77

    var element = document.querySelector('.class-selector-0');

  • DOM querySelectorAll( ) by tag name – 2.10

    var element = document.querySelectorAll('div')[0];

  • DOM querySelectorAll( ) by class name – 1.93

    var element = document.querySelectorAll('.general')[0];

  • DOM querySelector( ) by tag name – 1.46

    var element = document.querySelector('div:nth-child(0)');

  • DOM querySelector( ) by composed tag – 1.40

    var element = document.querySelector('section &gt; div:nth-child(0)');