开发者

Aquiring specific characters surrounded to specific tag

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 wh开发者_开发问答ich 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 and right side 10 or 20 chars.


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜