Using
$("a").attr("href", "http://www.google.com/")
will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:
<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>
...Then you probably don't want to accidentally add href
attributes to them. For safety then, we can specify that our selector will only match <a>
tags with an existing href
attribute:
$("a[href]") //...
Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href
, you might use something like this:
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
This will find links where the href
exactly matches the string http://www.google.com/
. A more involved task might be matching, then updating only part of the href
:
$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});
The first part selects only links where the href starts with http://stackoverflow.com
. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.
Best Answer
First of all let me refer to my previous answer — it contains some useful links you want to read first.
DOH can be used separately from Dojo, all you need is the "util" project where DOH resides. It has zero Dojo dependencies. In order to set it up for your own code, just take a look how Dojo does it. Usually the main file is called runTests.html. It is pretty much a boiler-plate, I just copy it over, and modify the URL in it to point to my own test module. For example, the Dojo Core tests' runTests.html uses "dojo.tests.module" ⇒ dojo/tests/module.js. Usually my directory is the peer to Dojo, so it will be something like "my.tests.module" located in my/tests/module.js or whatever I decide to name it.
Look in the Dojo's module.js — it includes other JavaScript files using
dojo.require()
(you can include and register your files with DOH without Dojo). It is possible to include files from different levels, or you can include a file (like dojo.tests._base) that includes more files. This is the way to make modular unit tests.It is possible to include HTML files as well. For example, dojo.tests._base.html does it.
In short: it is simple, just read the docs, and use existing Dojo tests as a cheatsheet.