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.