How to Use JQuery to Insert an Anchor
If you're thinking of working with Javascript for your next Web project, jQuery will make things a lot easier for you. jQuery is a Javascript library that is cross-browser compatible and simplifies the process of writing Javascript applications. One of the advantages of using Javascript is the ability to insert dynamic content into your Web page. You can easily select document object model (DOM) elements with jQuery's built-in DOM selector called "Sizzle." JQuery also simplifies the process of creating and inserting page elements, such as anchors, with its built-in functions "append()" and "prepend()."
Instructions
-
-
1
Create an empty file with the extension ".html" in your text editor. We'll create a basic HTML page that demonstrates how to insert an anchor into a pair of <div></div> HTML tags using jQuery.
-
2
Copy the following code into the file you just created. This will create the basic HTML structure and will import jQuery.
<html>
<head>
<title>Hello World</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'></script>
</head>
<body>
</body>
</html> -
-
3
Create an empty pair of <div></div> tags on your page with a unique ID; for our example, we will use "say_hello." This is where we will insert our anchors. You can do this by inserting the following code between the <body></body> tags:
<div id="say_hello">
</div>. -
4
Copy the following code into the <head> section of your HTML page. We will be using either the append() or prepend() jQuery library function to insert two anchors into the div we just created.
<script type='text/javascript'>
//<![CDATA[
$(function(){
$('#say_hello').append("<a href=\"www.google.com\">Hello!</a>")
$('#say_hello').prepend("<a href=\"www.bing.com\">Bye Bye!</a>")
});
//]]>
</script>You should now have a div on your page with two anchors inserted into it, one with anchor text "Hello!" and one with anchor text "Bye Bye!" The first anchor was appended to the div, and the second was prepended to the div.
-
1
Tips & Warnings
When using the append or prepend functions, make sure that you escape the quotations in the "href" part of your anchor with a backslash. Otherwise Javascript will interpret the quotation mark as an end-of-string marker and you will get an error.
References
Resources
- Photo Credit Comstock/Comstock/Getty Images