When I try to pass text which spreads throughout a few block elements the window.find method dosent work:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
<p>search me</p><b> I could be the answer</b>
</body>
</html>
JavaScript:
window.find("meI could be");
Or:
str = "me";
str+= "\n";
str+="I could be t";
window.find(str);
This happens when the <p>
element is present between the search term.
How can I fix that?
When I try to pass text which spreads throughout a few block elements the window.find method dosent work:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
<p>search me</p><b> I could be the answer</b>
</body>
</html>
JavaScript:
window.find("meI could be");
Or:
str = "me";
str+= "\n";
str+="I could be t";
window.find(str);
This happens when the <p>
element is present between the search term.
How can I fix that?
Share Improve this question edited Sep 16, 2012 at 7:06 funerr asked Sep 16, 2012 at 7:00 funerrfunerr 8,18617 gold badges90 silver badges139 bronze badges 2- Works fine in this fiddle (well in chrome anyway) – Musa Commented Sep 16, 2012 at 7:09
- @Musa, not in Firefox... (I neeed it to work at least with chrome, ff, safari and explorer). – funerr Commented Sep 16, 2012 at 7:25
1 Answer
Reset to default 3As option:
function containsStr(str) {
return document.body.innerText.indexOf(str) > -1;
}
Just tested it and it's working same as window.find. Or window.find is working same as this my function. Anyway seems it's depends to element's style.display property. E.g. when I set
p {
display: inline;
}
this call window.find("me I could be")
returns true
for your HTML example.
I created this example to test mentioned behavior.
As option you can create a div
element in memory, get document.body.innerHTML and set retrieved value to div's innerHTML
, then change style.dysplay
to "inline"
for elements within this div
similar to what I did in my code example, and then perform a search.
UPDATE #1: jQuery
I've made deeper research and found that usage of jQuery :contains
selector is working better than my previous function and than window.find, but may be more expensive (not sure, need to be tested).
function containsStr$(str) {
return $('body:contains("'+str+'")').length > 0;
}
UPDATE #2: pure JavaScript solution
function _find(str) {
var div = document.createElement('div');
div.innerHTML = document.body.innerHTML;
var elements = div.getElementsByTagName('*');
for(var i = elements.length; 0 > i--;) {
elements[i].style.display = 'inline';
}
return (div.innerText || div.textContent).indexOf(str) > -1;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745614565a4636154.html
评论列表(0条)