I'm looking for an easy way to locate elements on the page that have margin-left and margin-right set to auto.
I got this script, that helps me some of the time:
(function() {
var elementsList = [];
for (var i = 0; i < document.styleSheets.length; i++) {
var styleSheet = document.styleSheets[i];
if (styleSheet.rules) {
for (var j = 0; j < styleSheet.rules.length; j++) {
var rule = styleSheet.rules[j];
if (rule && rule.style && rule.style.marginLeft == 'auto' && rule.style.marginRight == 'auto') {
var smallList = document.querySelectorAll(rule.selectorText);
if (smallList.length)
elementsList = elementsList.concat(smallList);
}
}
}
}
return elementsList
})();
While this function gets some of the job done, it doesn't catch most cases of margin: auto
I've seen in websites.
Can you show me a better way?
getComputedStyles
to reliably filter elements withmargin-left/right
equal toauto
. Alsodocument.styleSheets
is smart but there is also a possibility of inline styles. That being said, the code is going to be pretty greedy as you need to scan many page elements. You can make it a little bit more efficient by skipping inline elements and elements like<br>
.0px
when margins are set toauto
even when they render correctly centered.