ROYAL OAK, Mich.—A challenge facing both political parties in the 2018 elections can be viewed along a two-mile stretch of road outside Detroit, where Republican voters have turned Democratic in recent years and Democratic voters have switched to the GOP.

On one end of 14 Mile Road is the wealthy suburb of Royal Oak, where straight-ticket Republican voters outnumbered Democrats as recently as 2000. But Donald Trump lost the city by 23 points in November.

Down the road is blue-collar Sterling Heights, which Barack Obama won in 2012 but Mr. Trump carried by 11 points in 2016.

Now, both parties are trying to recapture the voters they once counted as loyalists. Their success in Oakland County, where Royal Oak is located, and Macomb County, home to Sterling Heights, could decide the state’s midterm elections, which include races for the U.S. Senate and governor.

The voter shift in Oakland and Macomb counties is part of a larger pattern in U.S. politics, where densely-populated, well-educated, diversifying suburbs are trending Democratic, while whiter, blue-collar communities are moving the other way.