JAVASCRIPT GETELEMENT BY CLASS NAME

Lavanya



GetElementsByClassName()


The getElementsByClassName() method is used to select or retrieve elements based on their class name. This DOM method returns an array-like object containing all elements with the specified class name. When called on a specific element, it searches the entire document and returns only those elements that match the provided class name.

The argument "name" is required and must be a string that specifies either a single class name or multiple class names to match.

Example of getElementsByClassName()


Let's explore some examples to better understand the practical implementation of this method.

Example 


It is a straightforward class implementation that returns an array-like object when the variable x is invoked.


<!DOCTYPE html>
<html>
<head>
  <title>Array-Like Object</title>
</head>
<body>
  <h1>Array-Like Object</h1>
  <button onclick="console.log(x)">Log x</button>
  <button onclick="console.log(x[0])">Log x[0]</button>
  <button onclick="console.log(x.length)">Log x.length</button>
  <div id="result"></div>

  <script>
    class ArrayList {
      constructor() {
        this.length = 0;
        this.data = {};
      }

      push(item) {
        this.data[this.length] = item;
        this.length++;
      }

      get(index) {
        return this.data[index];
      }

      // Make it array-like

      [Symbol.toPrimitive](hint) {
        if (hint === 'string') {
          return JSON.stringify(this.data);
        } else {
          return Object.values(this.data);
        }
      }
    }

    let x = new ArrayList();
    x.push(1);
    x.push(2);
    x.push(3);

    // Display result
    document.getElementById("result").innerHTML = "x: " + x + "<br>x[0]: " + x[0] + "<br>x.length: " + x.length;
  </script>
</body>
</html>

Output:

x: [1, 2, 3]
x[0]: 1
x.length: 3

Difference between getElementsByClassName(), queryselector() and queryselectorAll() Methods


getElementsByClassName():


It selects elements with the specified class name and returns a set of matched elements. The returned elements form a live HTML collection, which automatically updates if any changes are made to the Document Object Model (DOM).

queryselector():


It returns the single element that matches the specified class name. If no matching element is found, it returns null.

The key takeaway is that while the methods mentioned above return either a single element or a list, the getElementsByClassName() method supports dynamic updates, whereas the other two methods provide static results.




Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send