As per Legend , Once Devi Parvathi, wanted to take a bath, there were no attendants around to guard her.. So she decided to make an Idol out out of dirt/sweat collected from her body, and with her divine powers Parvathi gave Life to that Idol, and gave him a task of guarding and warned him to not let anyone inside.

After some time, lord shiva came to Parvathi's palace and saw this little boy. Shiva asked the boy to let him in.. But Little boy stopped him saying mother has told, not allow anybody.. Though Shiva told he is Parvathi's husband, little boy refused to let him in. Lord shiva got angry and cut off the head of this new boy and threw it away using his trident.

At this time, Goddess Parvathi came back and became very sad, that the boy created by her was killed. Lord Shiva wanted to console Parvathi. So he sent his army to bring the first head that that they see on their way. The first head that they saw was the head of elephant. Shiva fixed that head on the boy’s trunk and brought him back to life. He also accepted him as his elder son and made him chief of his army.