I am trying to convert
style="border-top-left-radius: 20px; border-top-right-radius: 20px; border-bottom-right-radius: 20px; border-bottom-left-radius: 20px;"
into
style="border-radius: 20px" (or if the other corners are different corners have different values for it to be style="border-radius: A#px B#px C#px D#px")
I already have the file, and am trying to do the conversion using JS since this would be a regular thing.
I was trying to use something along the lines of
document.querySelectorAll('.possible-border-radius').forEach(node => {
...
}
but I am unsure how to manipulate the DOM afterwards.
Any help is appreciated!
Something like this would do in Vanilla:
// the selector is the class "c"; feel free to change it to anything
document.querySelectorAll(".c").forEach(node => {
const style = node.getAttribute("style").split(/; ?/g); // get the style of the node and split them into seperate styles
if (!style[style.length - 1]) style.pop(); // if the style ends with ";" get rid of it
let remainingStyles = []; // save all non-border-radius styles so we can add them again
let stack = style
.map(st => {
const data = st.split(/: ?/); // get the key and value of the css
return {
pos: data[0],
val: data[1]
};
})
// optional if you are accounting for extra CSS values:
.filter(st => /^border-(top|bottom)-(left|right)-radius$/.test(st.pos) ? true : (remainingStyles.push(st.pos + ": " + st.val), false));
const allTheSame = stack.every(v => v.val === stack[0].val); // Array.prototype.every returns true only if looping through the array the callback always returns true
if (allTheSame)
node.setAttribute("style", `border-radius: ${stack[0].val}; ` + remainingStyles.join("; ")); // all the same values! use the shorthand
else {
let template = "border-top-left-radius border-top-right-radius border-bottom-right-radius border-bottom-left-radius"; // a template for the placement
stack.forEach(i => {
template = template.replace(i.pos, i.val); // replace the template data with the template values
});
node.setAttribute("style", "border-radius: " + template + "; " + remainingStyles.join("; ")); // set the result
}
// for the demo:
console.log(node);
});
<div class="c" style="border-top-left-radius: 20px; border-top-right-radius: 20px; border-bottom-right-radius: 20px; border-bottom-left-radius: 20px; color: hotpink; background-color: blue;"></div>
<div class="c" style="border-top-left-radius: 10px;border-top-right-radius: 20px; border-bottom-right-radius: 30px; border-bottom-left-radius: 50px"></div>
<div style="border-top-left-radius: 20px; border-top-right-radius: 20px; border-bottom-right-radius: 20px; border-bottom-left-radius: 20px;"></div>