@@ -16,30 +16,42 @@ function targetTop()
16
16
} ) ;
17
17
}
18
18
19
- function addFigureAltText ( )
20
- {
19
+ function addFigureAltText ( ) {
20
+
21
+ // Helper function to wrap element with anchor
22
+ function wrapWithAnchor ( element , id ) {
23
+ const anchor = document . createElement ( 'a' ) ;
24
+ anchor . setAttribute ( 'name' , id ) ;
25
+ anchor . setAttribute ( 'id' , id ) ;
26
+
27
+ // Replace the element with the anchor
28
+ const parent = element . parentNode ;
29
+ parent . replaceChild ( anchor , element ) ;
30
+
31
+ // Add the element inside the anchor
32
+ anchor . appendChild ( element ) ;
33
+
34
+ return anchor ;
35
+ }
36
+
21
37
const images = document . querySelectorAll ( 'img' ) ;
22
38
var figureCounter = 1 ;
39
+
23
40
images . forEach ( ( img ) => {
24
41
if ( img . src . includes ( "/s-" ) ) {
25
42
img . title = `Figure ${ figureCounter } ` ;
26
-
27
- var anchor = document . createElement ( 'a' ) ;
28
- const anchorId = `figure${ figureCounter } `
29
- anchor . setAttribute ( 'name' , anchorId ) ;
30
- anchor . setAttribute ( 'id' , anchorId ) ;
31
- img . parentNode . parentNode . insertBefore ( anchor , img . parentNode ) ;
32
-
33
- // If it is a screenshot path add a second bookmark anchor
43
+
44
+ // Create figure number anchor
45
+ const figureAnchor = wrapWithAnchor ( img , `figure${ figureCounter } ` ) ;
46
+
47
+ // Add screenshot ID anchor if available
34
48
const match = img . src . match ( / \/ ( s - \d + ) / ) ;
35
49
if ( match ) {
36
- anchor = document . createElement ( 'a' ) ;
37
- anchor . setAttribute ( 'name' , match [ 1 ] ) ;
38
- anchor . setAttribute ( 'id' , match [ 1 ] ) ;
39
- img . parentNode . parentNode . insertBefore ( anchor , img . parentNode ) ;
40
- }
41
-
42
- figureCounter ++
50
+ // For the second ID, we need to wrap the already wrapped image
51
+ wrapWithAnchor ( figureAnchor , match [ 1 ] ) ;
52
+ }
53
+
54
+ figureCounter ++ ;
43
55
}
44
56
} ) ;
45
57
}
0 commit comments