Tyler Johnson
Tyler Johnson

Reputation: 927

How to get the text index of an element within a parent

Let's say I have the following html:

<div>
     <p>Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
     <p>Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vivamus sagittis lacus vel augue laoreet rutrum <i>faucibus</i> dolor auctor.</p>
</div>

See the buried <i>? I would like to get it's text offset in relation to the parent <div>, including all of the <p> tags and whitespace, but not including the parent <div>. In this example, the text offset would be 225-ish.

Is this doable with javascript?

Edit: Okay a little background. I have the full html saved as a string in a database so I know the exact content. I also have access to the actual <i> dom element. Now I need to match that dom element to its text offset.

Upvotes: 1

Views: 2509

Answers (2)

Jeff Noel
Jeff Noel

Reputation: 7618

Performance-wise

I would reccomend the pure way. JSPerf: See it by yourself


Pure Javascript

var div = document.getElementsByTagName('div')[0];
/* The index */
alert(div.innerHTML.lastIndexOf('<i>'));
/*The remaining HTML of the div*/
alert(div.innerHTML.substring(div.innerHTML.lastIndexOf('<i>'),div.innerHTML.length));

Alternative

document.getElemendById('myFirstItalicText');

jQuery

alert($('div').html().indexOf('<i>'));

Alternative

Add an id or a class to your <i> elements to find them easily.

$('#myFirstItalicText').css('background-color','red');

Upvotes: 2

John Cromartie
John Cromartie

Reputation: 4224

I think the answer, based on your requirements, is no.

The browser only provides the HTML of elements as a convenience, not as a substitute for the DOM API. The only way to reliably retrieve and manipulate elements is through the DOM.

You should only think of HTML as metadata for elements in the DOM.

Upvotes: 0

Related Questions