The jQuery scripting library is useful for adding and removing code to HTML document-based user actions, and you can also use jQuery scripting to animate parts of your Web pages. If you want to add tags around some text on a Web page, you can use the "wrap" function of jQuery. Select the text using a CSS selector -- code to target HTML tags -- in a function and then write your code to wrap tags around it.
- Skill level:
Other People Are Reading
Add the jQuery library to your Web page. Grab this code and put it somewhere above your closing </head> tag but above any other <script> tags:
The above code grabs jQuery from the Google Code server.
Write your "document ready" function between a new set of <script> tags somewhere below the tag that references the jQuery library. Here is how it looks:
// Your code will go here
The "document ready" function makes your jQuery code wait for the page to load before it tries to run. Using this will help prevent errors on your Web page.
Create a new function to select the part of your Web page that you want to wrap tags around. Select text by its tag name and then an ID or class name like you would in CSS. Look at the HTML file for your Web page to determine which tag to select.
Here is an example function:
// Code will go here
Change "selector" with a CSS selector such as "p .wrapme" for a <p> tag with a class name of "wrapme." When selecting by an ID, change the dot in front of the ID name to a hash symbol.
Copy and paste this code between the curly braces in your selector function:
$(this).wrap('<tagname>' + this + '</tagname>');
Change "tagname" to the name of the tag you want to wrap around your selected text. You can add attributes to the tag as well. In this code, "this" is shorthand for your selector. Your new tags will go outside the selected tags.
Tips and warnings
- Always save your HTML and CSS files before editing them.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for