Any moving electric charge creates a magnetic field around it. A loop of wire with a current creates a magnetic field through the loop. You can increase the strength of this field by piling up a lot of loops. The more loops, the stronger the magnet. Like a bar magnet, this coil of wire now has a north pole and a south pole, and is an electromagnet.
Because of the spin of electrons, which can be thought of as rotating balls of charge, each atom acts like a small magnet. Ordinarily, all these “loops” point in different directions, so the iron has no overall magnetism. But when you bring a nail near the south pole of your electromagnet, the north poles of the iron atoms will be attracted to the south pole of the electromagnet and they will all line up pointing in the same direction. The nail is now magnetized, with its north poles facing the south pole of the electromagnet. The opposite poles attract each other, so the nail is sucked into the electromagnet (click to enlarge diagram below).
When the direction of current is reversed, the poles of the electromagnet reverse. Knowing this, you might think that a nail inserted into the coil would now be repelled by the electromagnet. But when you try it, the nail is once again attracted and sucked into the coil. That’s because all of the nail’s iron atoms reorient to line up with whatever pole the electromagnet presents. Thus the nail will always be attracted to the electromagnet and will never be repelled.
You can find which end of the coil is the magnetic north pole with a magnetic compass or by using the right-hand rule: make a fist with your right hand, hold it parallel to the coil, and point your thumb in the direction the current is flowing (that is, away from the positive terminal of the battery and toward the negative terminal); your thumb will point to the north end of the coil.