The Spirit Bear

Written by Gray Gilmore

I make websites for a living. I love CSS and building simple and modular stylesheets. Somewhere along the way I also turned into a Ruby developer. Life comes at you fast I guess. You can read my resume to learn about my journey so far.

You can find me as @graygilmore on several platforms:

Good ol' fashion email works, too:

You can subscribe to this blog via RSS: XML, JSON

Using jQuery's wrap() with Variables

Since beginning my work at Pixel Union, I’ve become a bit of a jQuery freak. Well, that sounds like a bad thing but it’s really not. I went into the new job (that isn’t so ‘new’ anymore) with a pretty low level of jQuery knowledge. I could fiddle around with plugin options but that was it. Since then I’ve developed my own plugin (Extended Tumblr Photoset) and am using jQuery on every project.

I was having trouble in a recent project using the wrap() function and I couldn’t figure it out. I was trying to using it (actually, I was using wrapInner) on a variable from an ajax call and it just wouldn’t accept it. I was getting the following error:

Uncaught TypeError: Object 1 like has no method 'wrapInner'

What I was trying to do was simple enough, I just wanted to wrap some text in a link created from another variable:


It took a bit of searching on Stack Overflow to find my answer:

Second: if img hasn’t been appended to the document yet, then you can’t modify it in-place with wrap().

Bingo! I hadn’t appended someText to the document yet! Instead of wrapping and then appending, I just switched it up to appending then wrapping! After I append the text to the document, I just use this simple line to wrap it:


Just like that, everything is working as it should.


It’s been more than two years since I posted the above and I sure have come a long way in my JS knowledge. Still sticking with jQuery, here’s a much simpler way of doing this:

var div = $(someText).appendTo(document.body).wrapInner(someLink);

This way I don’t need to append someText and then traverse the DOM again looking for it. Hurray for simple solutions.