www.webdeveloper.com
Results 1 to 2 of 2

Thread: Finding a div that contains some text

Hybrid View

  1. #1
    Join Date
    Oct 2012
    Posts
    7

    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>

  2. #2
    Join Date
    Mar 2009
    Posts
    496
    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;
    }

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles