In Kaliningrad, Morocco took the lead after just 14 minutes.
Andres Iniesta's mix-up with Sergio Ramos gifted Morocco their first goal of the World Cup but the veteran midfielder quickly made amends by setting up Isco at the other end to bring Spain level at halftime in their last group match.
Khalid Boutaib pounced on the ball after the Spanish mistake near the halfway line in the 14th minute and sprinted into the area before he calmly shot underneath the advancing David De Gea.
Morocco, who lost their first two matches in Russia 1-0, only held onto a surprise lead against the 2010 World Champions for five minutes before Iniesta cut the ball back and Isco hammered it into the roof of Morocco's net from close range.
Substitute Youssef En Nesyri rose above Ramos to powerfully head home a corner in the 81st minute to give Morocco the lead back. But Iago Aspas secured top spot in the 91st minute with a back heel flick to make it 2-2.
In Saransk, Portugal were leading for most of the match until a controversial penalty, awarded after another video review, in the 93rd minute from Karim Ansarifard made it 1-1. An attempt on goal a minute later just went wide which would have booked Iran a spot in the second round.