Html find object by id

How To Access Elements in the DOM

In Understanding the DOM Tree and Nodes, we went over how the DOM is structured as a tree of objects called nodes, and that nodes can be text, comments, or elements. Usually when we access content in the DOM, it will be through an HTML element node.

In order to be confident in accessing elements in the DOM, it’s good to have a working knowledge of CSS selectors, syntax and terminology as well as an understanding of HTML elements. In this tutorial, you will learn several ways to access elements in the DOM: by ID, class, tag, and query selectors.

Overview

Here is a table overview of the five methods we will cover in this tutorial.

Gets Selector Syntax Method
ID #demo getElementById()
Class .demo getElementsByClassName()
Tag demo getElementsByTagName()
Selector (single) querySelector()
Selector (all) querySelectorAll()

It is helpful when studying the DOM to work with the examples on your own to ensure that you are understanding and retaining the information you learn.

Create a new file, access.html , in your own project to work through the examples along with this article. If you are unsure how to work with JavaScript and HTML locally, review our How To Add JavaScript to HTML tutorial.

DOCTYPE html> html lang="en"> head> meta charset="utf-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>Accessing Elements in the DOMtitle> style> html  font-family: sans-serif; color: #333; > body  max-width: 500px; margin: 0 auto; padding: 0 15px; > div, article  padding: 10px; margin: 5px; border: 1px solid #dedede; > style> head> body> h1>Accessing Elements in the DOMh1> h2>ID (#demo)h2> div id="demo">Access me by IDdiv> h2>Class (.demo)h2> div class="demo">Access me by class (1)div> div class="demo">Access me by class (2)div> h2>Tag (article)h2> article>Access me by tag (1)article> article>Access me by tag (2)article> h2>Query Selectorh2> div id="demo-query">Access me by querydiv> h2>Query Selector Allh2> div class="demo-query-all">Access me by query all (1)div> div class="demo-query-all">Access me by query all (2)div> body> html> 

In this HTML file, we have many elements that we will access with different document methods. When we render the file in a browser, it will look similar to this:

Browser rendering of access.html page

We’ll be using the different methods that we outlined in the Overview above to access the available elements in the file.

Accessing Elements by ID

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.

In order to be accessed by ID, the HTML element must have an id attribute. You have a div element with an ID of demo you can use:

div id="demo">Access me by IDdiv> 

In the Console, get the element and assign it to the demoId variable.

Logging demoId to the console will return our entire HTML element.

You can be sure you’re accessing the correct element by changing the border property to purple .

Once you do so, your live page will look like this:

Browser rendering of ID element styling

Accessing an element by ID is an effective way to get an element quickly in the DOM. However, it has drawbacks: an ID must always be unique to the page, and therefore you will only ever be able to access a single element at a time with the getElementById() method. If you wanted to add a function to many elements throughout the page, your code would quickly become repetitious.

Accessing Elements by Class

The class attribute is used to access one or more specific elements in the DOM. You can get all the elements with a given class name with the getElementsByClassName() method.

document.getElementsByClassName(); 

Now we want to access more than one element, and in our example we have two elements with a demo class.

div class="demo">Access me by class (1)div> div class="demo">Access me by class (2)div> 

Access these elements in the Console and put them in a variable called demoClass .

At this point, it might be tempting to modify the elements the same way you did with the ID example. However, if you try to run the following code and change the border property of the class demo elements to orange, you will get an error.

Output
Uncaught TypeError: Cannot set property 'border' of undefined

The reason this doesn’t work is because instead of just getting one element, you have an array-like object of elements.

JavaScript arrays must be accessed with an index number. You can change the first element of this array by using an index of 0 .

Generally when accessing elements by class, we want to apply a change to all the elements in the document with that particular class, not just one. You can do this by creating a for loop, and looping through every item in the array.

When you run this code, your live page will be rendered like this:

Browser rendering of class element styling

You have now selected every element on the page that has a demo class, and changed the border property to orange .

Accessing Elements by Tag

A less specific way to access multiple elements on the page would be by its HTML tag name. You access an element by tag with the getElementsByTagName() method.

document.getElementsByTagName(); 

For our tag example, we’re using article elements.

Access me by tag (1)
Access me by tag (2)

Just like accessing an element by its class, getElementsByTagName() will return an array-like object of elements, and you can modify every tag in the document with a for loop.

Upon running the code, the live page will be modified like so:

Browser rendering of tag element styling

The loop changed the border property of all article elements to blue .

Query Selectors

If you have any experience with the jQuery API, you may be familiar with jQuery’s method of accessing the DOM with CSS selectors.

$('#demo'); // returns the demo ID element in jQuery 

You can do the same in plain JavaScript with the querySelector() and querySelectorAll() methods.

document.querySelector(); document.querySelectorAll(); 

To access a single element, you can use the querySelector() method. In our HTML file, we have a demo-query element

div id="demo-query">Access me by querydiv> 

The selector for an id attribute is the hash symbol ( # ). You can assign the element with the demo-query id to the demoQuery variable.

In the case of a selector with multiple elements, such as a class or a tag, querySelector() will return the first element that matches the query. You can use the querySelectorAll() method to collect all the elements that match a specific query.

In the example file, you have two elements with the demo-query-all class applied to them.

div class="demo-query-all">Access me by query all (1)div> div class="demo-query-all">Access me by query all (2)div> 

The selector for a class attribute is a period or full stop ( . ), so you can access the class with .demo-query-all .

Using the forEach() method, you can apply the color green to the border property of all matching elements.

Browser rendering of querySelector() styling

With querySelector() , comma-separated values function as an OR operator. For example, querySelector(‘div, article’) will match div or article , whichever appears first in the document. With querySelectorAll() , comma-separated values function as an AND operator, and querySelectorAll(‘div, article’) will match all div and article values in the document.

Using the query selector methods is extremely powerful, as you can access any element or group of elements in the DOM the same way you would in a CSS file. For a complete list of selectors, review CSS Selectors on the Mozilla Developer Network.

Complete JavaScript Code

Below is the complete script of the work you did above. You can use it to access all the elements on our example page. Save the file as access.js and load it in to the HTML file right before the closing body tag.

// Assign all elements const demoId = document.getElementById('demo'); const demoClass = document.getElementsByClassName('demo'); const demoTag = document.getElementsByTagName('article'); const demoQuery = document.querySelector('#demo-query'); const demoQueryAll = document.querySelectorAll('.demo-query-all'); // Change border of ID demo to purple demoId.style.border = '1px solid purple'; // Change border of class demo to orange for (i = 0; i  demoClass.length; i++)  demoClass[i].style.border = '1px solid orange'; > // Change border of tag demo to blue for (i = 0; i  demoTag.length; i++)  demoTag[i].style.border = '1px solid blue'; > // Change border of ID demo-query to red demoQuery.style.border = '1px solid red'; // Change border of class query-all to green demoQueryAll.forEach(query =>  query.style.border = '1px solid green'; >); 

Your final HTML file will look like this:

DOCTYPE html> html lang="en"> head> meta charset="utf-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>Accessing Elements in the DOMtitle> style> html  font-family: sans-serif; color: #333; > body  max-width: 500px; margin: 0 auto; padding: 0 15px; > div, article  padding: 10px; margin: 5px; border: 1px solid #dedede; > style> head> body> h1>Accessing Elements in the DOMh1> h2>ID (#demo)h2> div id="demo">Access me by IDdiv> h2>Class (.demo)h2> div class="demo">Access me by class (1)div> div class="demo">Access me by class (2)div> h2>Tag (article)h2> article>Access me by tag (1)article> article>Access me by tag (2)article> h2>Query Selectorh2> div id="demo-query">Access me by querydiv> h2>Query Selector Allh2> div class="demo-query-all">Access me by query all (1)div> div class="demo-query-all">Access me by query all (2)div> script src="access.js">script> body> html> 

You can continue to work on these template files to make additional changes by accessing HTML elements.

Conclusion

In this tutorial, we went over 5 ways to access HTML elements in the DOM — by ID, by class, by HTML tag name, and by selector. The method you will use to get an element or group of elements will depend on browser support and how many elements you will be manipulating. You should now feel confident to access any HTML element in a document with JavaScript through the DOM.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Tutorial Series: Understanding the DOM — Document Object Model

The Document Object Model, usually referred to as the DOM, is an essential part of making websites interactive. It is an interface that allows a programming language to manipulate the content, structure, and style of a website. JavaScript is the client-side scripting language that connects to the DOM in an internet browser.

Источник

JavaScript HTML DOM Elements

This page teaches you how to find and access HTML elements in an HTML page.

Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are several ways to do this:

  • Finding HTML elements by id
  • Finding HTML elements by tag name
  • Finding HTML elements by class name
  • Finding HTML elements by CSS selectors
  • Finding HTML elements by HTML object collections

Finding HTML Element by Id

The easiest way to find an HTML element in the DOM, is by using the element id.

This example finds the element with id=»intro» :

Example

If the element is found, the method will return the element as an object (in element).

If the element is not found, element will contain null .

Finding HTML Elements by Tag Name

This example finds all

elements:

Example

This example finds the element with id=»main» , and then finds all

elements inside «main» :

Example

Finding HTML Elements by Class Name

If you want to find all HTML elements with the same class name, use getElementsByClassName() .

This example returns a list of all elements with class=»intro» .

Example

Finding HTML Elements by CSS Selectors

If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method.

This example returns a list of all

elements with class=»intro» .

Example

Finding HTML Elements by HTML Object Collections

This example finds the form element with id=»frm1″ , in the forms collection, and displays all element values:

Example

const x = document.forms[«frm1»];
let text = «»;
for (let i = 0; i < x.length; i++) text += x.elements[i].value + "
«;
>
document.getElementById(«demo»).innerHTML = text;

The following HTML objects (and object collections) are also accessible:

Источник

Читайте также:  Http forum materinstvo ru index php showtopic 32321 st 60
Оцените статью