diff --git a/app/assets/javascripts/merge_request_tabs.js.coffee b/app/assets/javascripts/merge_request_tabs.js.coffee
index 3e77ea515f819e36f3dca2fd0b641a25ab4cc267..593a8f42130d560598656814753d48df5fde3cde 100644
--- a/app/assets/javascripts/merge_request_tabs.js.coffee
+++ b/app/assets/javascripts/merge_request_tabs.js.coffee
@@ -68,8 +68,8 @@ class @MergeRequestTabs
 
   scrollToElement: (container) ->
     if window.location.hash
-      top = $(container + " " + window.location.hash).offset().top
-      $('body').scrollTo(top)
+      $el = $("#{container} #{window.location.hash}")
+      $('body').scrollTo($el.offset().top) if $el.length
 
   # Activate a tab based on the current action
   activateTab: (action) ->
@@ -127,7 +127,7 @@ class @MergeRequestTabs
         document.getElementById('commits').innerHTML = data.html
         $('.js-timeago').timeago()
         @commitsLoaded = true
-        @scrollToElement(".commits")
+        @scrollToElement("#commits")
 
   loadDiff: (source) ->
     return if @diffsLoaded
@@ -137,7 +137,7 @@ class @MergeRequestTabs
       success: (data) =>
         document.getElementById('diffs').innerHTML = data.html
         @diffsLoaded = true
-        @scrollToElement(".diffs")
+        @scrollToElement("#diffs")
 
   # Show or hide the loading spinner
   #