jQuery tag wrapping

Many times you’ll be working on something in HTML that could be long and repetitive, and then for some reason you need to edit the entire thing to wrap each of the tags on some other tags, a common example would be to link many elements.

Take this example, there’s a bunch of photos, they’re all contained in divs that have a css class called “photos”, inside we just throw
a bunch of <img> tags, and all of a sudden our boss tells us he wans to have every image on that page linked to “http://domain.com/photos”. jQuery to the rescue, no need to wrap each <img> with <a href=””> by hand, you can do it all in one line

So if the code looks like this:

       <div class="photos">
            <img src="http://domain.com/0670027481_m.jpg"/>
            <img src="http://domain.com/211161aa99_m.jpg"/>
            <img src="http://domain.com/173bb0cd6_m.jpg"/>
        </div>
        <div class="photos">
            <img src="http://domain.com/841fd90b5b_m.jpg"/>
            <img src="http://domain.com/52dda2cee5_m.jpg"/>
            <img src="http://domain.com/b569399599_m.jpg"/>
        </div>
        <div class="photos">
            <img src="http://domain.com/8806e863a4_m.jpg"/>
            <img src="http://domain.com/5e43aa95fe_m.jpg"/>
            <img src="http://domain.com/68a74a088c_m.jpg"/>
        </div>

        <div class="tshirt-photos">
            <img src="http://farm4.static.flickr.com/3149/3113619519_72ce82c545_m.jpg"/>
            <img src="http://farm4.static.flickr.com/3236/3105792155_99f2388869_m.jpg"/>
            <img src="http://farm3.static.flickr.com/2114/2372582266_765842fae9_m.jpg"/>
        </div>

With jQuery you can match all the <img> elements, and wrap them all with “<a href=”http://domain.com/photos”></a>” in a single line of code:

$(document).ready(function() { $(".photos img").wrap('<a href="http://domain.com/photos">') })

So to explain how it works, when the document is ready (when it’s finished loading) the function inside is called back, it will use the jQuery selector $(“.photos img”) to match all the <img> tags contained withing elements of css class “photos”, then it applies the wrap() function, which will wrap the matched elements with the given html tags.

About jQuery

jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML. It was released January 2006 at BarCamp NYC by John Resig.

Dual licensed under the MIT License and the GNU General Public License, jQuery is free and open source software.

jQuery contains the following features:

  • DOM element selections
  • DOM traversal and modification, (including support for CSS 1-3 and basic XPath)
  • Events
  • CSS manipulation
  • Effects and animations
  • Ajax
  • Extensibility
  • Utilities – such as browser version and the each function.
  • JavaScript Plugins

jQuery Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *