skip to Main Content

I want to manipulate a collection of DOM elements..

Here’s an Example:

HTML:

<div class="items">
  <p class="item">Here's some text</p>
  <p class="item">Here's another text</p>
  <p class="item">Here's some another text</p>
</div>

JS:

const items = document.querySelector(".item")

// This is how I do this vanilla JS way
items.forEach(item => {
  item.style.color = "#333"
})

// I want to achieve something like jQuery where we don't have to use loop

$(".item").css("color", "#333")

Thanks in advance!

I tried finding solutions but could not find the best solution.

2

Answers


  1. You can monkey patch the NodeList prototype or write an alike function/class/factory without monkey patching (like jQuery for example):

    NodeList.prototype.css = function(name, val){
      this.forEach(elem => elem.style[name] = val);
      return this;
    };
    
    class DomSet{
      constructor(nodelist){
        this.nodelist = nodelist;
      }
      css(name, val){
        this.nodelist.forEach(elem => elem.style[name] = val);
        return this;    
      }
    }
    
    const $ = function(selector){
      return new DomSet(document.querySelectorAll(selector));
    }
    
    document.querySelectorAll('.items .item')
      .css('color', 'red')
      .css('background', 'lightgray');
      
    $('.items2 .item')
      .css('color', 'blue')
      .css('background', 'yellow');
    <div class="items">
      <p class="item">Here's some text</p>
      <p class="item">Here's another text</p>
      <p class="item">Here's some another text</p>
    </div>
    
    <div class="items2">
      <p class="item">Here's some text</p>
      <p class="item">Here's another text</p>
      <p class="item">Here's some another text</p>
    </div>
    Login or Signup to reply.
  2. Here is one version that does not use a loop and it is really fast too:

    const someStyle = `<style>div.items .item { color: #333; }</style>`;
    
    document.head.insertAdjacentHTML('beforeend', someStyle);
    <div class="items">
      <p class="item">Here's some text</p>
      <p class="item">Here's another text</p>
      <p class="item">Here's some another text</p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search