Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript way to locate all elements with margin: auto

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?

like image 666
GuruYaya Avatar asked Nov 12 '14 10:11

GuruYaya


People also ask

How do you use margin auto?

The auto Value You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

Why does margin auto not work?

margin:auto won't work when you have a float or haven't specified a width. kohoutek: margin:auto won't work when you have a float or haven't specified a width.


1 Answers

If you're OK to use JQuery

As said by Martin Ernst for yonatan's answer: 'This will select only elements with marginLeft/Right="auto".'

Besides, as described in the comments, elements must be hidden in order to work with FF and safari.

This should work using JQuery:

$(document).ready(function() {
    var visibleElements = $('body *:visible');
    $('body *').hide();
    var elements = $('body *').filter(function() {
        return $(this).css('margin-left') == 'auto' && $(this).css('margin-right') == 'auto';
    })
    // show only elements that were visible
    visibleElements.show();
});

Tip: if for some reason, you need to not load external scripts, just copy the content of the minified jquery script at the begining of yours.

like image 68
Nicolas Avatar answered Oct 08 '22 01:10

Nicolas