songyy
songyy

Reputation: 4563

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.

Upvotes: 8

Views: 9513

Answers (5)

fregante
fregante

Reputation: 31718

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.

Upvotes: 2

Shadow
Shadow

Reputation: 9427

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"
);

Upvotes: 9

geckob
geckob

Reputation: 8128

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])
    }

}

Upvotes: 18

wbadart
wbadart

Reputation: 2911

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.

Upvotes: 1

Adnan Ahmed
Adnan Ahmed

Reputation: 686

Try this:

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

It will give you all elements having position fixed.

Upvotes: 0

Related Questions