If I have an element, for instance:
<p>Lorem ipsum dolor sit amet, ante risus massa adipiscing quisque quis. At mauris tellus in, sed vehicula integer fermentum rhoncus at faucibus, in vitae purus. Maecenas in vel ligula orci tellus ac, fringilla conubia lorem elit. Dui nulla sodales morbi vel. Massa sed viverra. Maecenas imperdiet donec urna a, ligula sed</p>
And this is flowed across multiple lines:
Lorem ipsum dolor sit amet, ante risus massa adipiscing quisque quis. At mauris tellus in, sed vehicula integer fermentum rhoncus at faucibus, in vitae purus. Maecenas in vel ligula orci tellus ac, fringilla conubia lorem elit. Dui nulla sodales morbi vel. Massa sed viverra. Maecenas imperdiet donec urna a, ligula sed
Is it possible to find out the position (in x,y-coordinates) of a particular character in the text using Javascript? If not, could I get the y-position of each line in the text?
Please note: There is a lot of text in the <p>
tag in my application, so adding <span>
around each character/word would be too much processing.
Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.
“how to position text in html” Code Answer's 1)static: this is the default value. 2)sticky: the element is positioned based on the user's scroll position. 3)fixed: the element is positioned related to the browser window. 4)relative: the element is positioned relative to its normal position.
Using CSS, you can center text in a div in multiple ways. The most common way is to use the text-align property to center text horizontally. Another way is to use the line-height and vertical-align properties. The last way exclusively applies to flex items and requires the justify-content and align-items properties.
If you know the string position of the character in the text, you can wrap the character in a <span> or similar element with an ID and find the x,y coords of that element. Easiest way to do this is with jQuery or another library, see this answer for a cross-browser, no-library method.
You can use ranges to find the position of elements. Quick jsfiddle here: https://jsfiddle.net/abrady0/ggr5mu7o/
var range = document.createRange(); range.setStart(parentElt, start); range.setEnd(parentElt, end); // These rects contain the client coordinates in top, left var rects = range.getClientRects();
Edit: modified to print out the coordinates of the matched rect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With