Abu Maimunah Sulaiman, the servant of the people of Madinah, narrates that I was sitting with Sayyiduna Abu Hurairah (may Allah be pleased with him) when a woman came to him and said, "My husband wants to take my child away." Sayyiduna Abu Hurairah (may Allah be pleased with him) said: I was present with the Messenger of Allah (peace and blessings be upon him) when a woman came to him and said, "My husband wants to take away my child or my son who serves me and brings me water from the well of Abu Anbah." The Messenger of Allah (peace and blessings be upon him) said: "You both cast lots," «استهما» he said, or «تساهما» he said, Abu Asim was uncertain about this (the meaning of both words is the same). Then the woman's husband came and said, "Who will dispute with me regarding my child or my son?" The Messenger of Allah (peace and blessings be upon him) said (to the child): "Son, this is your father and this is your mother, take the hand of whomever you wish to stay with." And Asim said: Go with whichever of the two you wish, so the boy took his mother's hand and she took him away.
From this hadith, it is understood that if separation occurs between husband and wife, the child will have the choice to stay with either the mother or the father, whichever he/she prefers.
This is the position of Imam Shafi‘i rahimahullah.
According to Imam Abu Hanifah rahimahullah, a young child will stay with the mother, and when the child is able to eat, drink, and clean himself/herself (perform istinja) independently, then the child will stay with the father, i.e., the child does not have a choice.
Furthermore, this hadith also proves that if there is a dispute between husband and wife regarding the children, then lots should be drawn; the children will stay with the one whose name is drawn. However, giving the child the choice is preferable, as most ahadith indicate this.
In Arabic, this is called the right of custody (haqq al-hadanah).
In the Saudi court, the law is that if separation occurs between husband and wife, the young boy or girl will remain with the mother until the age of discernment (sin al-tamyiz), i.e., up to seven years, provided that the woman does not remarry. In the case of a second marriage, the boy or girl will be transferred to the father.