Reputation: 4563
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
Reputation: 31718
Warnings that apply to all answers:
sticky
elements can act as fixed
elements in some casesHaving 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
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
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
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
Reputation: 686
Try this:
var elements = $('*').filter(function () {
return this.style.position == 'fixed';
});
It will give you all elements having position fixed.
Upvotes: 0