@@ -33,9 +33,12 @@ function scrollHeaders() {
3333 const headers = Array . from (
3434 document . querySelectorAll ( ":is(h1, h2, h3, h4, h5, h6)[id]" ) ,
3535 ) ;
36- const allShortcuts = Array . from (
37- document . querySelectorAll ( "#shortcuts > div" ) ,
38- ) ;
36+ const shortcuts = document . getElementById ( "shortcuts" ) ;
37+
38+ // Exit early if shortcuts container doesn't exist
39+ if ( ! shortcuts ) return ;
40+
41+ const allShortcuts = Array . from ( shortcuts . querySelectorAll ( "div" ) ) ;
3942
4043 headers . map ( ( currentSection ) => {
4144 // get the position of the section
@@ -81,22 +84,38 @@ function remToPx(rem) {
8184}
8285
8386function setupShortcuts ( shortcutDepth = 2 ) {
87+ // Find the shortcut target container in the sidebar
88+ const shortcutsTarget = document . getElementById ( "shortcuts" ) ;
89+
90+ /*
91+ * Exit early if shortcuts container doesn't exist
92+ * This is important to avoid errors when the theme
93+ * is used on pages that don't have the shortcuts sidebar
94+ */
95+ if ( ! shortcutsTarget ) {
96+ return ;
97+ }
98+
8499 shortcutDepth += 1 ; // to account for the page title
85100
86- // Build a class selector for each header type, and concatenate with commas
101+ // Build a class selector for each header level
87102 let classes = "" ;
88103 for ( let i = 2 ; i <= shortcutDepth ; i ++ ) {
89104 if ( i != 2 ) {
90105 classes += "," ;
91106 }
92- classes += " .content-container :not([role='tabpanel']) > h" + i ;
107+ classes += ` .content-container > h${ i } ` ;
93108 }
94109
95- // Content Page Shortcuts
96- const shortcutsTarget = document . getElementById ( "shortcuts" ) ;
97- if ( shortcutsTarget ) {
98- const classElements = Array . from ( document . querySelectorAll ( classes ) ) ;
110+ const classElements = Array . from ( document . querySelectorAll ( classes ) ) ;
111+
112+ // Only proceed if we found headers (to avoid creating an empty shortcuts section)
113+ if ( classElements . length > 0 ) {
99114 classElements . map ( ( el ) => {
115+ if ( ! el . id ) {
116+ return ;
117+ }
118+
100119 const title = el . innerHTML ;
101120 const elId = el . id ;
102121 // Gets the element type (e.g. h2, h3)
@@ -139,10 +158,13 @@ function setupShortcuts(shortcutDepth = 2) {
139158 const shortcuts = Array . from (
140159 document . querySelectorAll ( "#shortcuts div:not(#shortcuts-header)" ) ,
141160 ) ;
142- if ( shortcuts . length == 0 ) {
143- const shortcutsContainer = document . getElementById ( "shortcuts-container" ) ;
144- if ( shortcutsContainer ) {
161+ const shortcutsContainer = document . getElementById ( "shortcuts-container" ) ;
162+
163+ if ( shortcutsContainer ) {
164+ if ( shortcuts . length == 0 ) {
145165 shortcutsContainer . style . display = "none" ;
166+ } else {
167+ shortcutsContainer . style . display = "" ; // make shortcuts display visible, if hidden
146168 }
147169 }
148170
0 commit comments