/    Sign up×
Community /Pin to ProfileBookmark

Finding a div that contains some text

Hello colleagues

I have a web page with a lot of divs in it. Some of them contain names such as Smith, Ms Ruth.
I would like the page to load then perform the following code to find the Id of the div in which Ms Smith might be in.
The following code works well in a much smaller page with only 3 divs in it but does not seem to work with the large html page.
I have consulted google till my hair falls out.
Any ideas ?

Rory Barrett

<script id=”myScript”>
var surname = “”;
surname = prompt(‘What is name?’);
alert(surname);//works fine up to here

function getID()
{
$(document).ready(function(){
var z = $(“div:contains(surname)”);
alert(z[0].length);
});//doesn’t work ? But did on a smaller page
}
getID();

</script>

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@TcobbJun 25.2014 — This isn't tested. It also uses the "textContent" property which means it won't work with earlier versions of IE. It assumes that all your DIV's have an ID. If you send the word you're looking for as the arg it will return an array which will contain the ids of all DIV's in which that text occurs.

[CODE]function doFind(sought){
var i, len, arr, ids, div;
sought = sought.toLowerCase();
ids = [];
arr = document.getElementsByTagName('div');

len = arr.length;
for(i = 0; i < len; i++){
div = arr[i];
if(div.textContent.toLowerCase().indexOf(sought) >= 0){
ids.push(div.id);
}
}
return ids;
}[/CODE]
×

Success!

Help @Rory_Barrett spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...