The teams were closely matched through a nail-biting clash, with Spain having more of the ball but Morocco creating the better openings. Morocco will next face Portugal in the quarter-finals.
Underdogs Morocco knocked out Spain and became the first Arab country to reach the World Cup quarter-finals.
The two teams played out a draw after 120 minutes, with Spain having more of the ball but Morocco creating the better openings. until the Atlas Lions won 3-0 in the penalties.
Walid Regragui's side will face Portugal in what is uncharted territory for them, with their previous best being a last-16 exit in 1986.
After goals from Abdelhamid Sabiri and Hakim Ziyech, PSG defender Achraf Hakimi stepped up and scored the winning goal with a delightful chip.
Spain coach Luis Enrique had claimed his players prepared by taking 1,000 penalties as homework but Pablo Sarabia, Carlos Soler and Sergio Busquets all missed from the spot and Madrid-born Hakimi dinked his home to the delight of Morocco's raucous support.
Spain had been hoping they could repeat their 2010 World Cup triumph after reaching the semi-finals of Euro 2020, where they were also beaten on penalties by Italy.
Morocco will next face Portugal in the quarter-finals.
Watch the video on the player above.