With Morocco heading towards their first win of the tournament, Iago Aspas delivered the late heroics when he back-heeled the ball into the net to cancel out Youssef En-Nesyri`s brilliant 81st-minute header for Morocco.
The Spanish goal was awarded after a lengthy review by the Video Assistant Referee.
The first team eliminated from the World Cup following two 1-0 losses, Morocco began to play with the intensity that indicated they had every intention of returning home with a Spanish scalp and Khalid Boutaid put them ahead in the 14th minute.
Snatching the ball from Sergio Ramos in midfield Boutaid ran through alone and coolly slotted home between the legs of David de Gea for Morocco`s first goal of the World Cup.
With a last-16 spot on the line, the goal shocked Spain into action and Isco equalized for the 2010 world champions five minutes later, taking Andres Iniesta`s pass and crashing it into the roof of the net.
Spain nearly grabbed a second just before halftime when Iniesta fired a low pass across the goalmouth that a sliding Diego Costa just missed getting his foot to it.
Morocco returned to the pitch with renewed purpose after the break, taking the play to Spain and Nordin Amrabat nearly gave the North Africans the lead in the 56th minute when his thunderbolt from 25 yards clanged off the far post and crossbar.
It was Spain`s turn to go close next as Morocco defender Romain Saiss cleared Isco`s header off the line.
With time running out Spain finally began to play with urgency but could not find the equaliser until Aspas struck and his goal was finally given after a long wait for VAR confirmation.
Spain will play Russia in the last 16.