Blog>
Snippets

'this' in a DOM Manipulation Library

Implement a small DOM manipulation library function where 'this' refers to a collection of elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation Library</title>
<style>
  .highlight { background-color: yellow; }
</style>
</head>
<body>

<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<p class="text">Paragraph 3</p>

<script src="domlib.js"></script>
<script>
  // Use the library to highlight all paragraphs
  $('p.text').addClass('highlight');
</script>

</body>
</html>
This is the HTML structure with a linked JavaScript file (domlib.js) where our DOM manipulation library is defined. It includes the usage of the library to add a 'highlight' class to all paragraph elements with a class of 'text'. The CSS defines the styling for the 'highlight' class.
// domlib.js
(function(global) {
  function DOMLib(selector) {
    this.elements = Array.prototype.slice.call(document.querySelectorAll(selector));
  }

  DOMLib.prototype.addClass = function(className) {
    this.elements.forEach(function(element) {
      element.classList.add(className);
    });
    return this;
  };

  global.$ = function(selector) {
    return new DOMLib(selector);
  };
})(window);
This is the content of 'domlib.js'. It defines a small DOM manipulation library. The DOMLib constructor takes a selector and converts the NodeList from 'querySelectorAll' into an array. The addClass method is added to DOMLib's prototype, which allows adding a class to all elements in the collection. The global function $ is exposed to enable easy usage of the library.