JS snippets in working with DOM

JS snippets in working with DOM

Introduction

In this article, I tried to collect JavaScript code snippets (eng. code snippets), which can be useful in everyday work with DOM. Almost all snippets are written in two versions, using only plain JavaScript or with the help of the jQuery library.

js code snippets

Document Ready

The following examples show an “event listener” that waits for the moment when the DOM is loaded so that JavaScript can manipulate it. The same would be obtained if the JavaScript code were placed at the end of the body, i.e. before the closing “body” tag itself.



Document Load

The load event is “triggered” only when the entire page with all CSS styles, images

is loaded



Selecting DOM elements

Selection via CSS selector

HTML

JavaScript
Select all elements that satisfy the selector

Example

Selecting only the first element that satisfies the selector

If we want to return with plain JS only the first element that satisfies the selector criteria, we can use:

Syntax for older browsers

If there is a need to satisfy browsers older than IE 11, then the following JS selectors should be used:

Example

Select parent

HTML

JavaScript


Selecting all children

HTML

JavaScript

The following statements return an array of elements with all children of the selected selector. In the following examples, it is necessary to select all li elements:


NOTE:
It should be emphasized that “childNodes” returns as a child element even an empty space between HTML tags (as an empty text node)


Selecting the first child

HTML

JavaScript

If you want it to be the first child then the following commands can be used:


NOTE:
If there is an empty space between the parent tag and the first element that is its child, it will not return that element but an EMPTY text node.


Selecting the last child

HTML

JavaScript

NOTE:
If there is an empty space between the parent tag and the last element that is its child, it will not return that element but an EMPTY text node.


Selecting a previous relative

HTML

JavaScript

NOTE:
If there is an empty space between the parent tag and the last element that is its child, it will not return that element but an EMPTY text node.


Selecting the next relative

HTML

JavaScript

NOTE:
If there is an empty space between the parent tag and the last element that is its child, it will not return that element but an EMPTY text node.


Selecting all relatives

HTML

JavaScript

In this example, the function findRelatives creates a new array from the children of parents that satisfy the condition. Adds elements to the array if there is no filter or if the filter returns an element, as long as there is a next relative.

Filtering selected elements

Reducing elements that satisfy the targeted selector if they “pass” the filter test. The filter test can be another selector, and most often the filter is the function:

HTML

JavaScript

or using the function

Manipulation of DOM elements

Creating an element



Adding an element as a child

Adding a new element as the last child of each selected element.


NOTE:
Please note that the addition and assignment operator “+=” is used with innerHTML, because if only the assignment operator “=” is used, then when changing the DOM, all elements inside the “parent” element are stepped on and a new modified DOM is created, and if there are Event handlers that were attached to the “old DOM”, now NO THERE ARE!

I variant

II variant:

Clone element

If the parameter is “true”, a “deep copy” is made, i.e. copy with all attributes and “child” elements, while if “false” is selected it is copied without “child” elements.


Add before element

If referenceNode is null then it is inserted at the end of the list of all childNodes (same as appendChild).

Example of adding an element to a list

Adding after element

Although there is an insertBefore in JavaScript, there is NOT an insertAfter, so it is necessary to resort to a “cunning”:

Example of adding an element to a list

Deleting an element


Deletes ALL span elements

Deletes only span elements with ID=”selected”

Deleting all children of an element



Wrapping an element with an element

HTML

JavaScript


Result

Replacing an element with another

HTML

JavaScript

Example

Checking if selector (is) exists


Example

In the following snippets a boolean value is obtained, therefore if the answer is “true” then they are equal selectors. Mostly used with “if”.

Working with DOM content

Getting the content (text) inside the element

The following snippets return the text of the specified element:



Inserting or replacing content (text) within an element

The following snippets replace the existing text with new:



outerHTML element

HTML

JavaScript

For the HTML presentation of the selected element, we use:


One of the few cases where jQuery doesn’t have a direct method for a problem that Plain JS does, so it’s solved in a roundabout way (in a “temporary div element clones our element”).

Value inside “input” or “textarea”

Example

JavaScript

Example

JavaScript

Radio input

HTML

JavaScript

Select

HTML

JavaScript

Working with HTML attributes

GettingHTML attribute values

NOTE:
Attributes: href, title, alt, and value have their own “private” access property, so they can be easily accessed directly through them:
HTML

Other attributes that do not have their own “personal” method can be accessed as follows:



Getting the value of the DATA attribute

I must mention that this data can be obtained easily and in the previous way as a regular HTML attribute.

NOTE:
Do not use capital letters in the names of data attributes, but use dashes in between!

HTML

JavaScript

NOTE:
Use camelCase when calling as part of “dataset” syntax!


Setting attribute values

NOTE:
Attributes: href, title, alt, and value have their own “private” access property, so they can be easily accessed directly through them:
HTML

JavaScript


NOTE:
Added attributes are not physically visible in the DOM, but are stored in memory.

Checking if the element has a class

NOTE:
The classList object is not supported by IE for versions less than IE10


Adding a class to an element

NOTE:
The classList object is not supported by IE for versions less than IE10


Remove class

NOTE:
This classList object is not supported by IE for versions less than IE10


Alternate addition and deletion of class (togle)

HTML

JavaScript
No toggle()

See the Pen Toogle plainJS by Web programming (@chos) onCodePen.

From that()

NOTE:
This method is not supported in IE (see compatibility table here)

Example

Mix

Or mix the previous two examples

See the Pen EvaKoN by Web programming (@chos) on CodePen.


Example

Element styling

Getting element properties

Since the “getComputedStyle()” method returns the values of all properties in the form of “CSSStyleDeclaration” objects, it is also necessary to use the getPropertyValue method:

Example

Example

Defining CSS properties for an element

Defining a single property

Example

Defining multiple properties at once

Example

Defining property values

Defining multiple properties at once

Show, hide and toggle

NOTE:
Methods show() and toggle() require another attribute which can be: “block”, “flex” “inline-block”, “inline” …

Example

NOTE:
All three methods have “built-in” animation. If we want animation, it is enough to pass the attribute to the function that defines the duration of the animation. With these methods, width, height, and opacity are animated simultaneously. It is also possible to change the default animation type “swing” with another attribute.

Example

Element position

Element height and width

Box with padding and border

Similar can be obtained with getBoundingClientRect() method (supported >=IE9)

Box with podding, border and margin

Box without border

Box with padding and border

Box with podding, border and margin

Box without border

Distance of element to parent

The value from the edge of the selected element to the edge of the first “non-static” parent (one that does not have the position:”static” property). The left and upper edge of the element is observed.



Distance of the element to the document

Example

Similar can be obtained with the getBoundingClientRect() method:

Checking element visibility in viewport

With the following snippet, we check whether the selected element is entirely visible in the viewport.

Example

Scroll

The method that returns a value for how much the viewport of an element is scrolled is:

For window/document we can also use:

  • window.pageYOffset – not supported by version < IE9
  • window.scrollY – no support for IE
  • document.documentElement.scrollTop

But in order to achieve the greatest possible cross-browser compatibility, it is good to use the following expression:

See the Pen JS scroll by Web programming (@chos) on CodePen.


The method that returns a value for how much the viewport of an element is scrolled is:

See the Pen jQuery scroll by Webprogramming (@chos) on CodePen.


Mouse position at click event


If some other element is selected instead of the body tag, we will get a relative position in relation to it