Javascript to modify all absolutely positioned elements
-
18-09-2019 - |
Question
Effectively what I need to do in JS is move all absolutely positioned elements down by x pixels. Do I need to loop through every element and try to figure out if it's positioned absolutely? Or is there a better way?
Thanks, Mala
Update: specific: I am using a bookmarklet to inject JS onto any page - thus I cannot change the markup or actual css files in any way. This bookmarklet should, among other things, move all absolutely positioned elements 155 pixels down.
Solution
Something like this should do it:
function getStyle(el, prop) {
var doc = el.ownerDocument, view = doc.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(el, '')[prop];
}
return el.currentStyle[prop];
}
var all = document.getElementsByTagName('*'), i = all.length;
while (i--) {
var topOffset = parseInt(all[i].style.top, 10);
if (getStyle(all[i], 'position') === 'absolute') {
all[i].style.top = isNaN(topOffset) ? '155px' : (topOffset + 155) + 'px';
}
}
OTHER TIPS
You could tag all absolutely positioned elements with a specific class name and use the getElementsByClassName
in most browsers. Other than that, looping is the only option.
phoenix's solution un JQuery-ifed:
var nodes = document.getElementsByTagName("*");
node.foreach(function(n){ // can use foreach since this is FF only
if(n.style.position=="absolute"){
n.style.top += parseInt(n.style.top || 0, 10) +"px";
}
}
There is the CSS statement position: fixed
- that might do what you want...