I’m having issues with jQuery each() and find() methods in iOS Safari and on iOS devices.
squareTextWidth does not return anything in iOS, while on PC it returns the correct offsetWidth value. In fact squareText[0]
does not exist in Safari context.
console.log(squareText)
returns the DOM object in the JS console in Safari.
What am I doing wrong?
Is there a workaround?
function example() {
$('div.access').each(function() {
let squareText = $(this).find('.text');
let squareTextWidth = squareText[0].offsetWidth;
console.log(squareTextWidth);
});
}
example();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="access">
<span class="text">Example text 1</span>
</div>
<div class="access">
<span class="text">Example text 2</span>
</div>
<div class="access">
<span class="text">Example text 3</span>
</div>
<div class="access">
<span class="text">Example text 4 Longer text</span>
</div>
2
Answers
Ok so my
.text
is in fact an absolutely positionned<span>
with inline-flex and several other flex properties, and safari was unable to calculate offsetWidth, but other browsers could. Changed it to a<p>
tag and now it works fine.My mind was focused on the wrong part of the issue.
Thanks for your help.
You code seems to work in Safari iOS 16 Let’s see if this one works better in your Safari too:
You are in principle not getting what you think you are, and it seems some browsers do not mind and some do:
Result:
Chrome 111.0.5563.146 (Official Build) (x86_64) OSX
Safari OSX 16.3 (18614.4.6.1.6)
Safari iOS 16.4