According to Spanish news agency EFE, the uproar caused by the furious youngsters alerted police in the area of what was happening.
Upon being arrested, the Spanish citizen denied raping the child but later admitted having carried out the sexual attack.
His victim also confirmed he had been sexually abused.
The man is due to appear in a Marrakech court on Friday.
Under Moroccan criminal law, sex offenders are punished by up to 30 years in prison.
Local online daily Moroccan World News reported there has been a recent increase in sexual attacks on minors in the North African country.
The most recent ruling on July 17th sentenced a 57-year-old paedophile to only two years in prison after he was caught sexually abusing a 10-year-old child.