0

Imagine the following: You make a get request to a page and you receive its HTML as a response, same as a browser.

Without rendering it, how could you take that HTML string and figure out the x,y width and height properties of an element in the page programmatically?

Could I simulate rendering with some library in a hidden window, or can I simulate a window in js, simulate its rendering and use the normal methods to find these values?

Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
Fernando Bessa
  • 785
  • 1
  • 4
  • 10
  • 1
    width and height wont be calculated if an element is rendered on a page but made hidden. You won't be able to do it without the user noticing that a new window is opened and seeing its content – Below the Radar Aug 16 '18 at 15:04
  • You can render it but use `position: absolute;` and use `left: -99999;` or something like that to make sure users don't see it. Just make sure to remove the element from the DOM once you've got the stuff you need to clean it up. – dokgu Aug 16 '18 at 15:14
  • @uom-pgregorio That wouldn't solve his issue, since moving the element with the left attribute will affect the x value. – Devin Fields Aug 16 '18 at 15:15
  • Are you trying to get the element physical width or scroll width? – Matt D Aug 16 '18 at 15:16
  • 2
    @DevinFields Oh right.. for a second there I was only thinking of the width and height. If he wants.. he could put the `body` on `z-index: 2;` and put his elements on `z-index: 1;` so it will be behind what the users see. – dokgu Aug 16 '18 at 15:17
  • That actually might work, but I would use containers within the body. – Devin Fields Aug 16 '18 at 15:32

2 Answers2

0

I don't think you can; even if you could simulate some kind of standard rendering, for most elements the width and height could be affected by the user's browser settings, font size, accessibility settings, window size etc.

SimonDunne
  • 32
  • 1
  • 8
0

What you could do is to render the element behind the body. Make sure to apply a background color to the html element as mentioned here. Once you've rendered the element where the users can't see it, you can then grab all the stuff you need.

$(document).ready(function() {
  console.log("Width: " + $("#child").css("width"));
  console.log("Height: " + $("#child").css("height"));
  console.log("Left: " + $("#child").css("left"));
  console.log("Top: " + $("#child").css("top"));
});
html { 
  background-color: white;
}

body {
  background: #dadada;
  height: 100vh;
}
#child {
  width: 100px;
  height: 100px;
  background: yellow;
  position: relative;
  left: 65px;
  top: 50px;
  z-index: -1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="child">This should be hidden</div>
dokgu
  • 4,957
  • 3
  • 39
  • 77