An electromagnet works by passing a current of electricity through a coil of wire wrapped around an iron core such as a nail. The electricity from a battery creates a magnetic force around the nail when the wire is connected, allowing it to attract magnetic materials. Turning off the current by disconnecting the wire causes the magnetic force to disappear.