Append to attribute values using jQuery

Quite a productive day today, here’s another note to self containing a nice jQuery snippet that appends a string to a given attribute of a certain tag. I got the snippet from stackoverflow (of course).

<script>
  $.fn.appendAttr = function(attrName, suffix) {
    this.attr(attrName, function(i, val) {
        return val + suffix;
    });
    return this;
  };
</script>

I am doing some content work in a mixed php/perl/legacy web environment. I added some code to the part of the system that I have access to that hides the content I am working on unless I add a &preview in the URL. Because I part of the system that generates the menus, I had to add the &preview manually. This snippet allows me to stay in preview mode once I have entered preview mode.

<script>
  $( document ).ready(function() {
    if (window.location.href.match(/&preview$/).length > 0) {
        $( "a").appendAttr('href', '&preview')
    }
  });
</script>

Yay.

Advertisement