views:

37

answers:

1
A simple tool to store and display texts longer than a few lines.
The search button<div id="xyz">will highlight all</div> the words matching the name of objects that are members of the classes listed in searchedClasses, 
itself a member of the KeySet class. The highlighted words are hypertext.

I want to retrieve characters which are surrounded by div-xyz tag.
example output.
....search button will highlight all the words.....

I am able to get the current div tag text by following.

function myDivHTML(valueName){
     if((obj = document.getElementById(valueName)) && obj != null){
        return obj.innerHTML;
     }      
}

I tried with offsetParent property of element - but there are many possibilities like div tag may be inside bold tag & bold tag may be inside p tag & so on.

what should I do to get surrounding text ? limit may be 10, 20 chars.

Edit :

Surrounding text means -> text left side 10 or 20 chars & right side 10 or 20 chars.

Thanks in advance for sharing your knowledge. Sugar.

+2  A: 

The easiest way to do this, IMO is wrap the content of the inner div with obscure strings at either side then use a regular expression on the whole paragraph to find the markers you added along with the required number of characters at either side. Something like this:

var full, result,
    // textContent for w3 compliance, innerText for IE
    txt = "textContent" in document.body ? "textContent" : "innerText",
    // Get references to both divs and store the current text of `xyz`
    out = document.getElementById("outer"),
    xyz = document.getElementById("xyz"),
    old = xyz[txt];

// wrap the inner text with something we can easily search for:
xyz[txt] = "||||" + xyz[txt] + "||||";

// Get the whole text, change the DOM text back to what it was
full = out[txt];
xyz[txt] = old;

// Find the text with our markers and surrounding text:
result = /.{0,10}\|{4}.*?\|{4}.{0,10}/.exec(full);

alert(result[0]);
// -> "ch button ||||will highlight all|||| the words"

// Finally, replace your wrapping strings:
result = result[0].replace(/\|{4}/g, "");

alert(result);
// -> "ch button will highlight all the words"

You might want to adjust the regex slightly so that it matches, say, two whole words before and after the inner string.

Example
http://www.jsfiddle.net/Sy4rT/

Andy E
Is it possible to run this javascript on mobile-Safari(iPhone) ?
sugar
@sugar: there's no reason it shouldn't work on iPhone safari, but I'll check for you. **EDIT** worked fine. Theoretically, it should work in any modern browser that supports Javascript and innerText/textContent.
Andy E
OK ! Let me try out this one.
sugar
Perfectly working ! Bravo. Thank you very much.
sugar