Defenders Clark and Fernandez sent the Magpies on their way with first-half headers and Shelvey added their third in the 51st minute before Fabian Balbuena and Robert Snodgrass struck for West Ham to set up a dramatic finish.
The result lifted Newcastle to 15th place on 12 points from 11 games while West Ham, who stretched their winless league run to five games, slipped to 12th on 13 points.
Former Liverpool midfielder Shelvey was relieved his side were able to hang on after being pegged back by the home side in the closing stages.
"It's a great win, we dug deep in the last 20 minutes but I think we should have been at least four goals up in the first half," he told Newcastle United's television channel.
"We just need to be a bit more clinical and when you're down in the bottom half of the table, you have to take your chance as it comes."
Ireland centre-back Clark headed the visitors into a 16th-minute lead after good work by Joelinton and Shelvey before Fernandez took advantage of sloppy defending to double the advantage midway through the opening half.
Newcastle missed several chances to increase their lead before the interval as West Ham keeper Roberto Jimenez made three good saves and Shelvey hit the crossbar with a superb shot in the 35th minute.
Shelvey appeared to have sealed the game as a contest with a sublime finish before Balbuena pulled one back for West Ham and Snodgrass netted in the 90th minute, forcing Newcastle to defend desperately in stoppage time.