How to select html elements
It is recommended to use the jQuery library, which allows you to select elements and then apply an operation to all selected elements. But sometimes you need to do something in plain JavaScript.
The document object provides simple methods for selection of elements from html document.
method | description |
---|---|
getElementById(id) | Returns the first element with the specified id attribute value, otherwise a null value. |
getElementsByName(name) | Returns a collection of all elements with the specified attribute value name. Since HTML5 a name attribute was replaced with the id attribute. |
getElementsByClassName(cls) | Returns a collection of all elements with the specified class name. |
getElementsByTagName(tag) | Returns a collection of all elements with the specified tag name. |
querySelector(css) | Returns the first element that matches a given CSS selector. |
querySelectorAll(css) | Returns all elements in the document that matches a specified CSS selector. |
Node properties
The Node interface is base for some other interfaces: Document, Element, Attr and etc. It has some properties related with a document structure. So you can select children elements for any HTML element directly.
property | description |
---|---|
ownerDocument | The root element, in other words a document object. |
parentNode | The parent node of an node. |
childNodes | Collection of the children of this node. |
firstChild | The first child of an node. |
firstChild | The first child of an node. |
lastChild | The last child of an node. |
previousSibling | The element immediately before this node. |
nextSibling | The element immediately following this node. |