I am trying to get the width of an element to be able to set width of another element EXACTLY as big as the first one. The problem I am facing is that different broswers seem to give me different results, no matter the method I am using.
Basically I have an input field which I want to set to the size of the selected option. I use the following JS which fundamentally works fine:
var inputFields = document.querySelectorAll(".my-input-field");
// Resize on change
inputFields.forEach(function(element) {
element.addEventListener("change", function() {
resizeSelect(element);
});
});
function resizeSelect(sel) {
let tempOption = document.createElement('option');
tempOption.textContent = sel.options[sel.selectedIndex].textContent;
let tempSelect = document.createElement('select');
tempSelect.style.visibility = "hidden";
tempSelect.style.position = "fixed"
tempSelect.appendChild(tempOption);
sel.after(tempSelect);
sel.style.width = (parseInt(window.getComputedStyle(tempSelect).width) - 25) + 'px';
tempSelect.remove();
}
In this case I use window.getComputedStyle(tempSelect).width
to get the width which gives me 201px in Firefox and 196px in Edge (I haven’t tried more browsers yet). Where is this difference coming from?
I also tried to use tempSelect.offsetWidth
and tempSelect.getBoundingClientRect()['width]
with the same result.
Is there a browser independent solution that gives me the exact width of an element?