Kim Leadbeater sister of Jo Cox MP who was murdered in 2016, polled 13,296 votes to end the Conservatives' hopes of pulling another brick from the so-called "red wall".
Ryan Stephenson, a Leeds councillor and chairman of the West Yorkshire Conservatives, took 12,973 votes, failing to end Labour's 24-year hold on the constituency.
In the end it came down to just 323 votes.
Ms Leadbeater fought a campaign on local issues and said she was "absolutely delighted" that people in the area had "rejected division".
The Workers Party's George Galloway, who arrived in Batley on a mission to damage Labour leader Sir Keir Starmer, came third with 8,264 votes.
In a brief but emotional speech at Cathedral House in Huddersfield where the count took place, Ms Leadbeater said it had been "a gruelling few weeks" and thanked her family, friends, partner - and the police "who sadly I have needed more than ever over the last few weeks".
She said: "Without [my family] I would not have got through the last five years, never mind the last five weeks.
"There's lots to do, and I think the campaign has highlighted that there's lots to do.
"I will do my very best to represent the whole of Batley and Spen as their MP.
"I am absolutely delighted that the people of Batley and Spen have rejected division and they voted for hope."
It was a remarkable turnaround that confounded pundits and politicos alike, and augurs well for Sir Keir Starmer, who may well have found himself facing a leadership challenge on the back of two recent poor showings at the polls.
It was a strange atmosphere through the night as activists from the various parties sought to glean an early indication on voting patterns.
But even approaching 4am - just 90 minutes before the result was announced - many were reluctant to speculate on the eventual winner, saying it was just too close to call.
And indeed it was close - just 323 votes in it.
George Galloway's involvement in the by-election almost torpedoed Ms Leadbeater - plus potentially Sir Keir Starmer and the Labour Party as it stands.
But seeing how many votes he polled - and how many might have gone Labour's way - shows what the Labour majority could have been.
And it might have been a much bloodier nose for Prime Minister Boris Johnson after the thrashing that was Chesham and Amersham.