vijay khamitkar
Vj's Blog

Follow

Vj's Blog

Follow

JavaScript utility for daily work - part 2

vijay khamitkar's photo
vijay khamitkar
·Mar 26, 2023·

1 min read

Play this article

Table of contents

  • Adding multiple CSS styles to HTML elements using JavaScript
  • To get all the ancestors of the element in Dom
  • To find the closest ascending attribute value for the element.

Adding multiple CSS styles to HTML elements using JavaScript

const addStyles = (el, styles) => Object.assign(el.style, styles);

addStyles(document.getElementById('my_id'), {
  background: 'red',
  color: '#ffff00',
  fontSize: '3rem'
});
// before
// <div id="my_id" ></div>
//output after
// <div id="my_id" style="background:'red';  color:'#ffff00'; fontSize:'3rem'">Hello World</div>

To get all the ancestors of the element in Dom

const getAncestors = el => {
  let ancestors = [];
  while (el) {
    ancestors.unshift(el);
    el = el.parentNode;
  }
  return ancestors;
};

getAncestors(document.querySelector('nav'));
// [document, html, body, header, nav]

To find the closest ascending attribute value for the element.

function findUpEle(el, attr) {
        while (el.parentNode) {
            el = el.parentNode;
            if (el[attr]) {
                return el;
            }
        }
        return null;
    };
 document.body.onclick = function (event) {
    var closestElearttr = findUpEle(event.target, 'href');
    console.log(closestElearttr)
}
//Example - <div><a href="https://site02.in/"><span>Site02</span></a></div>
// output - https://site02.in/
 
Share this