NEW DELHI — What happens in a northern Indian town when you rip up someone else’s plants and saunter away?

You go to jail. Even if you’re a donkey.

News this week that eight donkeys had been jailed for four days for eating expensive saplings went viral in India, drawing a mix of ridicule and good-hearted laughs.

The Indian government has been on a cleanliness kick, led by Prime Minister Narendra Modi, who has vowed to build tens of millions of toilets and clean up garbage in cities. According to the authorities, the donkeys were making a mess.

“We had warned the donkey owners a couple of times, but they didn’t pay heed,” said R.K. Mishra, a police constable, according to an interview that was broadcast on an Indian news channel.

Television footage showed the donkeys, in the town of Orai in Uttar Pradesh state, plodding out of a scruffy jail, walking single file, heads bowed. The way the scene was filmed made it look like a classic police perp walk.

Police officials in Uttar Pradesh accused them of eating young plants that had been put near the jail as part of a cleanup campaign. The plants were worth almost $1,000, the authorities said.

Many were quick to mock the authorities. “Dear UP Police,” one person wrote on Twitter, using the abbreviation for Uttar Pradesh. “How about arresting real criminals instead of donkeys?”

The donkeys’ owner, identified only as a young man named Kamlesh, had no idea at first what had happened to his animals and went on a frantic search, according to The Times of India.

When he learned the donkeys had been incarcerated, he pleaded with police officers to release them. The officers refused.

So Kamlesh did what many people do in India when they hit a sticky spot with the law: He found a politician.

He persuaded a local leader from Mr. Modi’s political party, the B.J.P., to accompany him to the jail, and this time the outcome was different.

All eight donkeys were set free on Monday. Police officials said Kamlesh signed a statement that “from now on he will not allow his animals to roam in residential areas or places of public importance.”