I'm trying to create a script with Greasemonkey that limits the border-radius on all elements of a webpage to a maximum of 2px, hoping to make websites appear less visually cluttered. Here's the code I'm using:
```javascript
(function() {
'use strict';
function enforceBorderRadius(element) {
const currentRadius = window.getComputedStyle(element).getPropertyValue('border-radius');
const radiusValue = parseFloat(currentRadius);
if (!isNaN(radiusValue) && radiusValue > 6) {
element.style.setProperty('border-radius', '2px', 'important');
}
}
function applyToAllElements(rootElement) {
const elements = rootElement.querySelectorAll('*');
elements.forEach(enforceBorderRadius);
}
applyToAllElements(document.body);
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
applyToAllElements(mutation.target);
});
});
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: false,
});
})();
```
The script works for some elements, but not all. I'm curious about what I might be missing or if there's something wrong with the approach I'm using.
2 Answers
It seems like Reddit uses Shadow DOM for some of its elements, which means they can be isolated from the main document structure. Your script might not be applying styles to those Shadow DOM elements. You might need to look into how to access those specific elements if it's necessary to enforce your styles on them.
One potential issue is that if the current border-radius is set with units (like em or %), `parseFloat` might not work correctly. You'll have to extract just the numeric part from the string. I suggest using a regex to get the numeric value.
Related Questions
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String