How do I increase the lightness(or the l
property) of a hsl
color.
Ie if I have an element
<div class="myDiv" style="background-color:hsl(240,100%,50%)">My div</div>
How do I use JavaScript or jQuery to change the lightness of the div
.
There are multiple choices, but here's one that changes only the lightness:
var div = document.getElementsByClassName('myDiv')[0];
var newLightness = '70%';
div.outerHTML = div.outerHTML.replace(/(hsl\(.*?,.*?,).*?(\))/, '$1' + newLightness + '$2');
This will edit only the lightness on the div's outerHTML.
Explanation:
The HSL property cannot be fetched from the style
attribute due to w3's standarts, but the HSL is still present in the DOM, so we just replace the current's div 3rd parameter to the HSL function in the inline style, we use regex with capturing groups to catch what comes before and after the lightness parameter, and by that replacing only the lightness.
Even if the element has inner elements with the HSL inline style, only the first one will be changed, because the g
flag wasn't specified in the regex.