Accessing HTML Elements from JavaScript


1 Comment


When the browser reads your HTML code, it creates something called the DOM (Document Object Model). The DOM is basically an interface that can be used to access or modify any of the HTML tags (elements) on your page.


var myButton = document.querySelector('#myButton');

The code shown above retrieves the element with id="myButton" from the DOM and stores it in a new variable called myButton. myButton can now be used to access or manipulate the button.

Notice that we tell querySelector which element we want by passing it a CSS selector. These are the same selectors you use to select elements you want to style in a CSS file.

If the selector passed to querySelector would select more than 1 elemenet, only the first element is returned.


Works exactly the same as querySelector -- except it returns all the elements that match the CSS selector (not just the first).

Using querySelector to find elements inside another element


<form id="loginForm">
    <input type="text" name="userName">

    var loginForm = document.querySelector('#loginForm');

    // Search inside loginForm only
    var userName = loginForm.querySelector('input[name=userName]');

Notice that we used loginForm.querySelector instead of document.querySelector to get the userName. What's the difference? Well, instead of searching the entire document, we're only searching inside #loginForm.

This technique wasn't necessary in this situation, since the form had a unique id, but you'll sometimes need to do this when doing more complicated things. It also should offer better performance (if you already have the container saved to a variable), since it won't have to search the whole page.

Old ways for getting elements from the DOM

  • document.getElementById('theId');
  • document.getElementsByTagName('ul');
  • document.getElementsByClassName('theClass');

I mainly mention these because you will still see them in old code.

querySelector and querySelectorAll are much more powerful than these old methods and are fully supported in all modern browsers (including Internet Explorer 9 (IE9) and above). IE8 and below currently only make up 0.20% of the browser market worldwide, so I wouldn't worry about supporting them.

One Response

  • Nagaraj October 24, 20181:25 am

    Best javascript tutorial


Leave a Comment