JavaScript utility for daily work - part 2
Play this article
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/