Combine pure string and jQuery object. A word about outerHTML property

You can’t simply combine pure string and jQuery object using Javascript concatenation operator (+). You cannot easily mix strings and DOM elements. So, something so trivial like surrounding link with [ and ] brackets becomes not so trivial. At least to beginners. This article should help.

Since we can’t easily combine pure string and jQuery object (DOM element), this will not work:

    photoTitle = $(this).attr('title'),
    galleryLink = $('<a>".Yii::t('app', 'start slideshow')."</a>'),
    downloadLink = $('<a>".Yii::t('app', 'download image')."</a>').attr('href', $(this).attr('href'));

return photoTitle + ' [' + downloadLink + ']';

You’ll end up with texts combined with [object Object] string.

You can convert string to jQuery object / DOM element (using for example .parseHtml()) or create a new DOM element from that string, using many various techniques. And, if you don’t have an element in your string, only some text (like in above example), simply use this:

var photoTitle = $($(this).attr('title'));

to convert text value to jQuery object.

You can then do all the magic on such object, like using .append() or .add() or any of the vast jQuery DOM manipulation methods.

And what about the opposite way? If you want to get jQuery object / DOM element as pure string, to actually use Javascript concatenation operator (+) to combine such elements? Well… here you go, outerHTML property is your friend! Since, it isn’t implemented in jQuery yet (nobody knows, why?), then you can either use .prop() method to apply this one time:

    photoTitle = $(this).attr('title'),
    galleryLink = $('<a>".Yii::t('app', 'start slideshow')."</a>').prop('outerHTML'),
    downloadLink = $('<a>".Yii::t('app', 'download image')."</a>').attr('href', $(this).attr('href')).prop('outerHTML');

return photoTitle + ' [' + downloadLink + ' | ' + galleryLink + ']';

Or you can extend jQuery with your own implementation of .outerHTML() method, for general usage.

Leave a Reply