"Water hammer" is the result of any sudden change in pressure or flow in a pipe. Liquids (water) don't compress or expand, so when there is a sudden change in pressure or flow, the kinetic energy of the liquid gets converted to an energy shock wave that travels up and down the pipes looking for a place to dissipate, in this case as mechanical movement of the pipes themselves, likely because of poor or old failing bracing. Injecting foam (more later) is only going to move the problem to some other area and likely make things WORSE.
The CORRECT way of dealing with this is to have some sort of "shock arrestor" installed in your piping system somewhere. This can be a complex device, or in many cases just a vertical pipe somewhere with air trapped in it, because air DOES compress. In some old houses where people have done modifications or additions, they find these old trapped air pipes, cannot figure out what they were for, then use them as "free connections" for the addition / modification and thus unwittingly remove their essential function. You need to make sure you have some form of water hammer suppression, otherwise the problem persists until a pipe bursts inside of the wall.
Injecting foam, aside from masking the issue instead of solving it, also runs the risk of damaging your floor. It can be VERY VERY tricky to make sure you don't inject TOO MUCH foam because if the space available is too limited for the amount of expansion it will have, you can end up with it blowing out your floorboards or the ceiling below, causing more problems than it solved. Resist the temptation for a quick fix...