简体   繁体   中英

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.

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');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM