Spain dominated possession in the first half but could not find a way past a resolute Morocco defence. The best chance of the half came when Morocco defender Nayef Aguerd headed over from close range.
The 2010 World Cup champions enjoyed more than 75% of possession and completed almost 800 passes but could not find a breakthrough inside 90 minutes, sending the game to extra time. Morocco had the better chances as they squandered a pair of one-on-ones and, with the scores still level, a penalty shootout was required.
The times were divided in experience -- it was Morocco's first shootout at a World Cup finals and Spain's fifth -- but Morocco goalkeeper Yassine Bounou turned hero, watching Spain first spot kick hit the post before saving their next two efforts. Defender Achraf Hakimi then stepped up with a chance to win it, chipping his penalty in superb style claim a 3-0 victory in the shootout.
It was the fourth time Spain have been knocked out of the World Cup on penalties and the second in a row.
"We fought and made the Moroccan people happy, we made history and Morocco deserve it, Moroccan people made us united on the pitch," coach Walid Regragui told Bein Sports.
Morocco defender Jawad El Yamiq was proud of his team's performance.
"We honoured the Arab and African football, coach Regragui gave us the confidence that we needed in this game, a big boost in morale," he said.
"We knew that Spain depend on their ball possession and we played with that in mind. They didn't impose any danger."
The Spanish spent big chunks of the match orbiting around the Morocco penalty area without attempting any shots, through balls or moves to break down their well organised opponents.
They tried to play the possession-style game that was the trademark of the great Spanish sides who won two European Championships and the World Cup between 2008 and 2012, but they lacked a cutting edge, and Morocco allowed them possession while trying to exploit the pace of Hakim Ziyech and Soufiane Boufal.
A foul on the latter gave the African side the first scoring opportunity as Hakimi blazed over a free kick.
In a tight first half, the only other chances came when defender Aguerd headed over and Spain midfielder Marco Asensio hit the side-netting for Spain.
Dani Olmo had Spain's first shot on-target in the 54th minute with a angled shot which Bounou palmed away.
Head coach Enrique sent on Alvaro Morata and Nico Williams to inject a bit of life into his team and Morocco had to dig deep to get through extra-time without conceding.
They managed to do so and Spain's collapse in the shootout prompted wild celebrations among the ecstatic Morocco supporters who will get at least one more chance to make their presence felt in Qatar.
Information from Reuters contributed to this report.