File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree File renamed without changes.
Original file line number Diff line number Diff line change 11function fetchComic ( ) {
22 const container = document . getElementById ( "comic-container" ) ;
3- const loading = document . getElementById ( "loading" ) ;
43
54 fetch ( "https://xkcd.now.sh/?comic=latest" )
65 . then ( response => {
@@ -12,22 +11,33 @@ function fetchComic() {
1211 . then ( data => {
1312 console . log ( data ) ;
1413
15- if ( loading ) loading . remove ( ) ;
14+ // CLEAR OLD CONTENT
15+ container . innerHTML = "" ;
1616
17- container . innerHTML = `
18- <h2>${ data . title } </h2>
19- <img src="${ data . img } " alt="${ data . alt } " />
20- <p>${ data . alt } </p>
21- ` ;
17+ // SAFE ELEMENT CREATION (FIXES XSS)
18+ const title = document . createElement ( "h2" ) ;
19+ title . textContent = data . title ;
20+
21+ const img = document . createElement ( "img" ) ;
22+ img . src = data . img ;
23+ img . alt = data . alt ;
24+
25+ const desc = document . createElement ( "p" ) ;
26+ desc . textContent = data . alt ;
27+
28+ container . appendChild ( title ) ;
29+ container . appendChild ( img ) ;
30+ container . appendChild ( desc ) ;
2231 } )
2332 . catch ( error => {
24- console . error ( error ) ;
33+ container . innerHTML = "" ;
34+
35+ const errorMsg = document . createElement ( "p" ) ;
36+ errorMsg . textContent = "Error loading comic 😢" ;
2537
26- if ( loading ) {
27- loading . textContent = "Error loading comic 😢" ;
28- } else {
29- container . innerHTML = `<p>Error loading comic 😢</p>` ;
30- }
38+ container . appendChild ( errorMsg ) ;
39+
40+ console . error ( error ) ;
3141 } ) ;
3242}
3343
You can’t perform that action at this time.
0 commit comments