How could I get the text of the body that is before a specific element using Javascript/jQuery?
What I want to achieve is finding out the position of an element respect of the body, for instance, if the body text is 100 characters long and the text before the node is 50, that node would be at 50%.
Getting body’s length is easy, but getting the text before an element is not as trivial as I’d thought in first instance.
EDIT:
To make it clear, I’ll give an example:
<body>
<p>
...some text <span>that could have sub-elements</span>
</p>
<p>
...some text
<ul>
<li>now with a list</li>
<li>why not?</li>
</ul>
</p>
<div>
<p>...some text...</p>
<div>
<p>...some text...</p>
<p id="this_is_the_element">what's there in the body before this element?</p>
<p>...some text...</p>
<p>...some text...</p>
</div
</div>
</body>
In this case, the specific node would be #this_is_the_element and what I would expect to get is something like:
...some text that could have sub-elements
...some text
now with a list
why not?
...some text
...some text
I can propose this function :
The trick is to insert a unique marker and get the text until this marker. Of course the inserted element is removed before the HTML is rendered. It will work for any kind of body.
Demonstration (open the console)
EDIT :
Demonstration with the HTML of your edit (open the console)