Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Get Id of div with certain text as innerHTML

    Hello Colleagues

    I have a task whereby I have to find the id of a div which might contain a name such as Smith, Ms Ruth.
    I successfully used the following code to do this when there were only 4 divs but this code does not work with the large html page which I need to make it work.

    The code is:

    <script id="myScript">
    var surname = "";
    surname = prompt('What is name?');
    alert(surname);

    function getID()
    {
    $(document).ready(function(){
    var z = $("div:contains(Adcock, Ms B)");
    alert(z[0].length);
    });//doesn't work ?
    }
    getID();

    /*
    var myScript = document.getElementById('myScript');
    var myId = myScript.parentNode.id;
    */
    var myId = document.getElementsByClassName('c')[0].id
    //alert(myId);

    </script>


    Any help you can give will be most gratefully accepted.

    Rory Barrett

  • #2
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,280
    Thanks
    12
    Thanked 342 Times in 338 Posts
    you need to quote the strings you’re looking for within :contains().
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #3
    Regular Coder
    Join Date
    Aug 2010
    Posts
    970
    Thanks
    19
    Thanked 212 Times in 210 Posts
    this...
    alert(z[0].length);

    should be
    alert(z.length);

    try this code ...


    Code:
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>contains demo</title>
      <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body> 
    <div id="id1">John Resig Adcock, Ms B</div>
    <div id="id2">George Martin</div>
    <div id="id3">Malcom John Sinclair Adcock, Ms B</div>
    <div id="id4">J. Ohn</div>
    <script> 
      function getID()
     {
     $(document).ready(function(){
      var z = $("div:contains(Adcock, Ms B)").css( "text-decoration", "underline" );;
      alert(z[0].id + " " + z[1].id);
     });
     }
     getID();
     </script>
    </body>
    </html>
    Last edited by DaveyErwin; 06-25-2014 at 11:08 PM.


  •  

    Posting Permissions

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