BARCELONA, Spain — Spain’s effort to snuff out an independence drive in Catalonia was dealt a significant blow on Thursday as secessionists narrowly won an election called by Prime Minister Mariano Rajoy in hopes of calming the country’s constitutional crisis.

After Catalonia’s separatist lawmakers declared independence in late October, Mr. Rajoy invoked emergency powers for the first time in Spain’s democratic history. He ousted the Catalan government and imposed direct rule on the formerly autonomous region.

Mr. Rajoy then called new elections for the regional Parliament, hoping to reshuffle the political deck and calculating that Catalan voters would punish the secessionist leaders. Many are now being prosecuted for sedition and rebellion and campaigned from prison or exile.