Search Page For String Within HREF

deharvy
deharvy used Ask the Experts™
on
I need javascript code that will search all the links on the page and then search for a string value within the href.

Here is an example of the link: <a href="http://www.sample.com/index.jsp?UserIDExample=1111111">

-----------------

Here was my failed attempt:

            if ( document.getElementsByTagName('a').href.indexOf("UserIDExample") > -1 ) {
                        alert("found");
                  else
                        alert("not found);
            }
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
With straight-up plain 'ol javascript, this oughtta do it:

var allLinks = document.links;
for (var i=0; i<allLinks.length; i++) {
  if (allLinks[i].href.indexOf("UserIDExample") > -1){
  	alert(1);
  }
}

Open in new window

And for in your particular use:

var allLinks = document.links;
var found = false;
for (var i=0; i<allLinks.length; i++) {
  if (allLinks[i].href.indexOf("UserIDExample") > -1){
   found = true;
  }
}
if (found){
 alert("found");
} else {
 alert("not found");
}

Open in new window

Author

Commented:
Excellent stuff. Thanks!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial