简体   繁体   中英

Get all elements with `position:fixed` in an HTML page?

Reason for doing that: I'm debugging css of my webpage.. some elements appeared and they're not supposed to appear. I suspect it is the issue with element positioning.. therefore I want to find these positioned element and check one by one.

This one is using jQuery. I hope you are find with it.

 var find = $('*').filter(function () { 
        return $(this).css('position') == 'fixed';
    });

I think this one works using a pure javascript:

var elems = document.body.getElementsByTagName("*");
var len = elems.length

for (var i=0;i<len;i++) {

    if (window.getComputedStyle(elems[i],null).getPropertyValue('position') == 'fixed') {
        console.log(elems[i])
    }

}

Here is an ES6 version that gives you an array of these elements for further processing:

let fixedElements = [...document.body.getElementsByTagName("*")].filter(
    x => getComputedStyle(x, null).getPropertyValue("position") === "fixed"
);

document.querySelector('*[style="position:fixed"]')

The * item specifies all tag names. The [] indicate that you're looking for an attribute. You want your style attribute to have position:fixed .

If you aren't using jQuery, this is probably going to be your simplest option.

Try this:

var elements = $('*').filter(function () { 
    return this.style.position == 'fixed';
});

It will give you all elements having position fixed.

Warnings that apply to all answers:

  • This is a slow operation. On a large-enough page, this operation can take 100ms or more, which is a lot for a single operation. You shouldn't need this unless you're developing a browser extension.
  • Now sticky elements can act as fixed elements in some cases

Having said that, here's the shortest and most efficient version to do this:

const fixed = [].filter.call(document.all, e => getComputedStyle(e).position == 'fixed');

Here's a version that includes sticky elements, but they're not exactly equivalent, it depends on what you're looking for:

const all = [].filter.call(
  document.all,
  e => ['fixed', 'sticky'].includes(getComputedStyle(e).position)
);

If you're feeling modern , replace document.all with document.querySelectorAll('*') , but the former will likely work forever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM