Other presidents have been knocked off stride by special elections that ultimately presaged greater defeats. In 1991, George Bush was stunned when his attorney general, Dick Thornburgh, lost a special election for Senate against Harris Wofford, a little-known Democrat whose strategists went on to help Bill Clinton topple the incumbent president a year later.

In 2010, Barack Obama was likewise thrown by the election of Scott Brown, a Republican, to fill a vacant Senate seat in heavily Democratic Massachusetts. The election not only cost Democrats their filibuster-proof supermajority just as they were trying to pass health care legislation, but it also foreshadowed a Republican landslide in midterm elections later that year.

“It becomes the chink in the armor of the person who just a year before or 18 months before was the most popular figure in the country,” recalled Jennifer Psaki, a veteran of Mr. Obama’s White House. “For us, it was certainly the case that you have a moment of depressed sulking. And then you have to pick yourself up and figure out how to move forward.”

For Mr. Obama, the special election forced a strategic re-evaluation. Some aides advised him to trim his ambitions for health care and seek a narrower bill. But Mr. Obama opted to push for his original, more sweeping legislation. Ultimately, he pushed it through without Republican backing, but it never developed bipartisan support and remains a target of efforts to repeal it.

For Mr. Trump, who has already endured off-year Republican election defeats in New Jersey and Virginia, Alabama has now delivered not one but two humiliating defeats in a state that he won by 28 percentage points just a year ago. In a Republican primary to fill the Senate seat vacated by Jeff Sessions, now the attorney general, Mr. Trump first endorsed Luther Strange, the choice of the party establishment, only to watch him lose to Mr. Moore, who was backed by Mr. Bannon.

Undeterred by allegations that Mr. Moore sought sexual contact with teenagers as young as 14, Mr. Trump endorsed him against the advice of White House advisers. But as he sat watching the results in the White House residence on Tuesday, alone for much of the evening with the first lady out of town, Mr. Trump once again saw his preferred candidate defeated, in this case by Doug Jones, a Democrat in a state that had rebuffed Democrats for decades.