The HTML DOM search property associated with the anchor tag (<a>) returns the query string part of the href property value. The query string part is after the ? in a url and is usually used to pass information to the server. It is used when a get request is sent to the server and information is embedded in cleartext in the link.
Syntax
Following is the syntax for
a) Returning the search property
anchorObject.search
b) Setting the search property
anchorObject.search = querystring
Example
Let us see an example of HTML DOM anchor search property −
<!DOCTYPE html> <html> <body> <p><a id="myAnchor" target="_blank" href="https://www.examplesite.com/ex.htm?id=Username">Example Site</a></p> <p>Click the button to change the querystring part of the above website</p> <p>Inspect the url before clicking the button to inspect the changes</p> <button onclick="demo()">Change Search</button> <script> function demo() { document.getElementById("myAnchor").search = "program=Sample"; } </script> </body> </html>
Output
This will produce the following output −
Before checking ‘Show Form ID’ checkbox −
Without clicking on button “Change Search”, the links are as follows −
www.examplesite.com/ex.htm?id=Username
After clicking on the button “Change Search”, the link would be −
www.examplesite.com/ex.htm?prog=Sample
In the above example −
We have taken an anchor tag with search property to manipulate the search property value to set or return the search string value.
<p><a id="myAnchor" target="_blank" href="https://www.examplesite.com/ex.htm?id=Username">Example Site</a></p>
We have then created a button named “Change Search” to execute the myFunction() −
<button onclick="demo()">Change Search</button>
The myFunction() will change the search string part from id=”Username” to program=Sample
function demo() { document.getElementById("myAnchor").search = "program=Sample"; }