Lina Hidalgo never thought she would work in politics or run for office.

She and her family fled their home country of Colombia as a drug war raged, arriving in the United States in 2005. She studied law, public policy and political science at elite universities as she pursued a career influencing government from the outside.

But on Tuesday, Ms. Hidalgo, a 27-year-old Democrat, narrowly won an upset election to lead Harris County, which includes Houston and is the third-most populous county in the country and the largest in Texas. She beat the 11-year Republican incumbent to become the first woman and the first Latina elected to the county judge office.

Ms. Hidalgo said she decided to run for office after the 2016 election because of the divisiveness it displayed. She ran as an outsider candidate.

“I’m not tied to the powers that be,” she said in an interview on Thursday. “People were inspired. Their hearts led them to speak up in a year in which our democracy seemed to be under threat.”