A purported member of the MS-13 gang broke into the bedroom of a sleeping 11-year-old Brooklyn girl and raped her in her bed, cops said Saturday as the suspect was taken into custody.

The horrific crime happened at 11:30 p.m. Wednes­day in Prospect-Lefferts Gardens, officials said.

The suspect — identified by police sources as El Salvadoran immigrant Julio Cesar Ayala, 18, who lives nearby — had allegedly climbed onto the roof of the girl’s apartment building.

He then somehow shoved aside the girl’s window air conditioner on the second floor and crawled inside through the opening, police sources said.

The fiend raped the girl in her bed, officials said.

But he dashed back out the window as she screamed to alert her mother, who rushed to her aid, sources said.

The mother called 911 but did not catch sight of the attacker, the sources said.

By luck, though, police were able to grab video-surveillance images of the suspect.

On Saturday at 2:35 p.m., some 30 officers from the NYPD’s Emergency Service Unit and the 70th Precinct converged on ­Ayala at his hideaway in an under-construction three-story building at 930 Flatbush Ave.

They pulled out the scrawny, hunched man, who was seen handcuffed and dressed in filthy black jeans and a red T-shirt.

Ayala — who police sources said carried a federal Permanent Resident Card, also known as a “Green Card,” as his only identification — was led struggling into a police SUV.

A high-level police source told The Post that investigators believe Ayala is a member of the violent MS-13 gang.

Cheers and taunts rose from a crowd of dozens of spectators as Ayala was hauled out. Some applauded and took cellphone pictures.

“They got him!” one man yelled.

“He raped somebody, an 11-year-old girl,” another onlooker said.

Ayala was charged Saturday night with sexually motivated burglary and first-degree rape.

He has no previous criminal record, sources said.

The crime shocked residents in the girl’s tidy neighborhood of two- and three-story homes.

“That makes me feel unsafe in my own home,” said Elizabeth Bardourilla, 42, a mental-health counselor.

“That child can’t help herself. For a grown man to do that. Sick. Very sick. This is sad. Just sad.”

“That’s horrible,” added David Cadogan, 40, a paramedic.

“I got a son and nieces. I don’t play with stuff like that. There’s past a point where you tolerate certain behaviors.

“I know people want to wait on the law. But if anything happens to him between now and then, I honestly don’t care. He gets what he deserves.”

Additional reporting by Paul Martinka