0

i am writing some code which need to access a div which contains the particular text following is the small portion of code i am working on:

var txtElem = txtdiv.getElementsByTagName("div");
txtElem[9].style.border = "2px solid blue";

as seen above i am accessing particular div with the index number, but now i want to add more code which can return me index of div from txtElem which contains the selected text from page

Mark Walters
  • 12,060
  • 6
  • 33
  • 48
hiteshtr
  • 443
  • 2
  • 5
  • 20

4 Answers4

2

You need to loop trough the divs and check the contents with innerHTML

Willem D'Haeseleer
  • 19,661
  • 9
  • 66
  • 99
  • @hiteshtr , if you want to get the selection of the user you might want to look into this thread : http://stackoverflow.com/questions/845390/javascript-to-get-paragraph-of-selected-text-in-web-page – Willem D'Haeseleer Apr 11 '12 at 09:56
1

Try the code below

 var txtElem = txtdiv.getElementsByTagName("div");

 for ( var i = 0; i < txtElem.length; i++) {
    if(txtElem[i].innerHTML === "The text in the div") {
       //i is the index of the div that contains the text you searched on
       alert(i);
    }
 }
Mark Walters
  • 12,060
  • 6
  • 33
  • 48
0

Loop through divs and use JQuery .html() to check the html content of the div element.

dapperwaterbuffalo
  • 2,672
  • 5
  • 35
  • 48
0

For ease of use you may want to use jquery see http://api.jquery.com/contains-selector/

Shaun Hare
  • 3,771
  • 2
  • 24
  • 36