SAN SALVADOR — Salvadorans elected Nayib Bukele, the media-savvy former mayor of the capital, as their next president on Sunday, delivering a sharp rebuke to the two parties that emerged from the country’s brutal civil war in the 1980s and have held power ever since.

The dramatic win for Mr. Bukele, 37, who was running as an outsider, underscores the deep discredit into which the country’s traditional parties have fallen. Voters appeared to be willing to gamble on a relative newcomer to confront the country’s poverty and violence, shutting out the right- and left-wing parties that have dominated Salvadoran politics for three decades.

Mr. Bukele won almost 54 percent of the vote in preliminary results, the electoral board said, beating out Carlos Calleja, a supermarket executive who was the conservative Arena Party candidate. Hugo Martínez, a former foreign minister who ran for the governing Farabundo Martí National Liberation Front, or F.M.L.N., saw many of his party’s voters defect to Mr. Bukele and came in a distant third.

“Today we have turned the page on the postwar period,” Mr. Bukele said, appearing in blue jeans and his trademark leather jacket to declare victory.

Attacks from both the left and the right seemed to have little effect on Mr. Bukele’s popularity, which was driven by a social media campaign portraying him as a reformer willing to take on the ossified political establishment.

The conservative Nationalist Republican Alliance, known as Arena, was founded in 1981 by the extreme-right leader Roberto D’Aubuisson, who was accused of organizing death squads during the civil war. During its two decades in government, Arena recast itself as a business-friendly party, although it has never disowned its founder.