Javascript Element - 32 Methods (Reference)

Tech:
Javascript
Since:
1 year ago
Views:
5

In Javascript, HTML elements can be accessed by using various selectors. The selected element provides methods which can be used to manipulate the elements.

CONTENT_1

click()

Simulates a mouse click on an element.

var x = document.getElementById("id_name");
x.click();

focus()

Sets focus on the specified element.

var x = document.getElementById("id_name");
x.focus();

blur()

Removes keyboard focus from the current element.

var x = document.getElementById("id_name");
x.blur();

getAttribute()

It returns the value of a specified attribute on the element.

var x = document.getElementById("some_id");
var y = x.getAttribute("class");

// "some_class_name"

getAttributeNames()

It returns the attribute names of the element as an Array of strings.

var x = document.getElementById("id_name");
var y = x.getAttributeNames();
// ["id", "class"]

getElementsByClassName()

It returns a collection of all elements with the specified class name.

// Get all elements by class
var x = document.getElementsByClassName("class_name");

// Get first element by class
var x = document.getElementsByClassName("class_name")[0];

// Get all elements of both classes
var x = document.getElementsByClassName("class_name1 class_name2");

// Get all elements inside id by class
var x = document.getElementById("id_name").getElementsByClassName("class_name");

getElementsByTagName()

It returns a collection of all elements with the specified tag name.

// Get all span elements
var x = document.getElementsByTagName("span");

// Get all div elements
var x = document.getElementsByTagName("div");

// Get all div elements inside the id
var x = document.getElementById("id_name");
var x = a.getElementsByTagName("div");

closest()

It traverses the Element and its parents until it finds a node that matches the provided selector string.

var x = document.getElementById("id_name");
var y = x.closet("#some_id");
var y = x.closet("div > span");
var y = x.closet(":not(div)");
// HTML element

matches()

Checks to see if the Element would be selected by the provided selectorString. Checks if the element "is" the selector.

var x = document.getElementsByTagName("div");
for (var i = 0; i < x.length; i++) {
  if (x[i].matches(".class_name")) {
    // code
  }
}

getBoundingClientRect()

It returns the size of an element and its position relative to the viewport.

var x = document.getElementById("id_name");
var y = x.getBoundingClientRect();
// DOMRect {x: 16, y: -2292, width: 1357, height: 3327.84375, top: -2292, …}

getClientRects()

It returns a collection of DOMRect objects that indicate the bounding rectangles for each CSS border box in a client.

var x = document.getElementById("id_name");
var y = x.getClientRects();
// DOMRectList {0: DOMRect, length: 1}

hasAttribute()

It returns a Boolean value indicating whether the specified element has the specified attribute or not.

var x = document.getElementById("id_name");
var y = x.hasAttribute("class");
// true

hasAttributes()

It returns a Boolean value indicating whether the specified element has the specified attribute or not.

var x = document.getElementById("id_name");
var y = x.hasAttributes("class");
// true

insertAdjacentElement()

Inserts a given element node at a given position relative to the element it is invoked upon.

var x = document.createElement('span');
document.body.insertAdjacentElement('afterend', x);


// beforebegin
  el open tag
    // afterbegin
  content
    // beforeend
  el close tag
// afterend

insertAdjacentHTML()

Parses the text as HTML or XML and inserts the resulting nodes into the tree in the position given.

document.body.insertAdjacentElement('afterend', 'HTML el as text');


// beforebegin
  el open tag
    // afterbegin
  content
    // beforeend
  el close tag
// afterend

insertAdjacentText()

Inserts a given text node at a given position relative to the element it is invoked upon.

document.body.insertAdjacentElement('afterend', 'Some text');


// beforebegin
  el open tag
    // afterbegin
  content
    // beforeend
  el close tag
// afterend

releasePointerCapture()

It releases pointer capture that was previously set for a specific pointer.

var x = document.getElementById("id_name");
x.releasePointerCapture(pointerId);
//

hasPointerCapture()

Sets whether the element on which it is invoked has pointer capture for the pointer identified by the given pointer ID.

var x = document.getElementById("id_name");
x.hasPointerCapture(pointerId);

requestPointerLock()

It asynchronously ask for the pointer to be locked on the given element.

var x = document.getElementById("id_name");
x.requestPointerLock();

setPointerCapture()

It designates a specific element as the capture target of future pointer events.

var x = document.getElementById("id_name");
var y = x.setPointerCapture(pointerId);

scroll()

Scrolls to a particular set of coordinates inside a given element.

var x = document.getElementById("id_name");
x.scroll(0, 100);

x.scroll({
  top: 100,
  left: 100,
  behavior: "smooth"
});

// no safari support

scrollBy()

Scrolls an element by the given amount.

var x = document.getElementById("id_name");
x.scrollBy({
  top: 100,
  left: 100,
  behavior: "smooth"
});

// no safari support

scrollTo()

Scrolls to a particular set of coordinates inside a given element.

var x = document.getElementById("id_name");

x.scrollTo(0, 1000);

x.scrollTo({
  top: 100,
  left: 100,
  behavior: "smooth"
});

// no safari support

scrollIntoView()

Scrolls to a particular set of coordinates inside a given element.

var x = document.getElementById("id_name");

x.scrollIntoView();
x.scrollIntoView(false);
x.scrollIntoView({ block: "end" });
x.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });

// alignToTop
// If true, the top of the element will be aligned to the top of the visible area
// If false, the bottom of the element will be aligned to the bottom of the visible area

// behavior
// Defines the transition animation.
// One of auto or smooth. Defaults to auto.

// block
// Defines vertical alignment.
// One of start, center, end, or nearest. Defaults to start.

// inline
// Defines horizontal alignment.
// One of start, center, end, or nearest. Defaults to nearest.

setAttribute()

Sets the value of a named attribute of the current node.

var x = document.getElementById("id_name");
x.setAttribute("name", "some_name");

toggleAttribute()

It is used to add or remove an attribute from an element. It toggles a Boolean attribute.

var x = document.getElementById("id_name");
var y = x.toggleAttribute("readonly");

removeAttribute()

It removes the attribute with the specified name from the element.

var x = document.getElementById("id_name");
x.removeAttribute("class");

getAnimations()

It returns an array of all Animation objects.

var x = document.getElementById("some_id");
var y = x.getAnimations();

var x = document.getAnimations();

animate()

This method animates the element. It takes an object of key-value pairs of properties and values that the element should be animated to.

document.getElementById("id_name").animate(
  [
    // keyframes
    { transform: "translateY(0px)" },
    { transform: "translateY(-300px)" }
  ],

  // timing options
  { duration: 1000, iterations: Infinity }
);

// var animation = element.animate(keyframes, options);

// keyframes
// Either an array of keyframe objects, or a keyframe object
// whose property are arrays of values to iterate over

// options
// Either an integer representing the animation's duration (in milliseconds)
// or an Object containing one or more timing properties
// id,delay,direction,duration,easing,endDelay,fill,
// iterationStart,iterations,composite,iterationComposite

attachShadow()

It attaches a shadow DOM tree to the specified element and returns a reference to its.

var x = document.body.attachShadow({ mode: "open" });
var y = document.createElement("span");

x.appendChild(y);

// Mode : open
// Elements of the shadow root are accessible from JavaScript outside the root

// Mode : closed
// Denies access to the node(s) of a closed shadow root from JavaScript outside it

// Elements that can attach a shadow root to:

// Custom element with a valid name,article,aside,blockquote,
// body,div,footer,h1,h2,h3,h4,h5,h6,header,main,nav,p,section,span,

requestFullscreen()

It asynchronous request to make the element be displayed in full-screen mode.

var x = document.getElementById("id_name");

x.requestFullscreen().catch(err => {
  // code
});

computedStyleMap()

It returns a StylePropertyMapReadOnly interface which provides a read-only representation of a CSS declaration block.

var x = document.getElementById("id_name");
var y = x.computedStyleMap();
// StylePropertyMapReadOnly {size: 316}