Introduction
This page shows you how to add an attribute to a number of elements using JQuery. Below are some sample links to popular web sites. Before applying JQuery update button, links open the in the current window. Apply the JQuery script by clicking on the update button below. After this update a border is added to all the links on the page. In addition, the links should now open in a new window. Notice that even the navigation links have a border added. This is done by using the addClass
method to add the .blueBorder
class to the links.
Sample Links
Here is the source code for the example.
JavaScriptAddAttribute.html
Get Source
The script tag for including JQuery is not shown in the source code.
1 <!-- Start Main Content -->
2 <div id="main">
3 <style type="text/css">
4 .blueBorder{ border: 1pt solid blue; }
5 </style>
6
7 <h4>Introduction</h4>
8 <p>This page shows you how to add an attribute to a number of elements using JQuery. Below are some sample links to popular web sites. Before applying JQuery update button, links open the in the current window. Apply the JQuery script by clicking on the update button below. After this update a border is added to all the links on the page. In addition, the links should now open in a new window. Notice that even the navigation links have a border added. This is done by using the <code>addClass</code> method to add the <code>.blueBorder</code> class to the links.</p>
9 <h4>Sample Links</h4>
10 <ul>
11 <li><a href="http://www.amazon.com">Amazon</a></li>
12 <li><a href="http://www.google.com">Google</a></li>
13 <li><a href="http://www.yahoo.com">Yahoo</a></li>
14 </ul>
15 <button class="update">Update</button>
16 <p>Here is the source code for the example.</p>
17 <p class="codetitle"><a href="source/JavaScriptAddAttribute.src.html.html" target="_blank">JavaScriptAddAttribute.src.html</a></p>
18 <iframe class="CodeFrame" src="source/JavaScriptAddAttribute.src.html"><p><a href="source/JavaScriptAddAttribute.src.html">source/JavaScriptAddAttribute.src.html</a></p></iframe>
19
20 <script type="text/javascript">
21 function addAttributes(){
22 $('a[href]').attr('target', '_blank');
23 $('a[href]').addClass("blueBorder");
24 }
25
26 function pageLoad(){
27 $('button.update').click(addAttributes);
28 }
29
30 $(document).ready(pageLoad);
31 </script>
32
33
34 </div>
35 <!-- End Main Content -->
36