Struggling with modifying HTML using Javascript? Take a look at this example: https://jsfiddle.net/02mwyvyo/
The objective is to shift a specific element downwards on the page. This involves inserting a spacer div
before the target element, with style attributes
style="display: inline-block; width=1px; height=100px;"
.
Check out the code snippet below:
function describeDOMRect(rect) {
return "{ top: " + rect.top + ", left: " + rect.left + ", bottom: " + rect.bottom + ", right: " + rect.right + " }"
}
function addVerticalSpacer() {
var div = document.getElementsByClassName("target-div")[0]
var bounds = div.getBoundingClientRect()
console.log("old bounds: " + describeDOMRect(bounds))
var spacerHeight = 100
var newTop = bounds.top + spacerHeight
var spacer = document.createElement("div")
spacer.className = "spacer"
spacer.setAttribute("style", "display: inline-block; width: 1px; height: " + spacerHeight + "px;")
div.parentNode.insertBefore(spacer, div)
bounds = div.getBoundingClientRect()
console.log("new bounds: " + describeDOMRect(bounds))
}
Furthermore, here are the CSS properties for the div
:
div {
border: none;
border-width: 0;
padding: 0;
margin: 0;
}
Upon running the above code, you may notice these results in the console:
old bounds: { top: 26, left: 8, bottom: 26, right: 729 }
new bounds: { top: 112, left: 8, bottom: 112, right: 729 }
Despite expecting the new position to be 126 based on the initial top value of 26, it shows up as 112 instead.
If you're wondering why this discrepancy occurs and how to fix it, let's delve into the details!