While it might seem strange that "pet" comes from a word that means "attack," the connection lies in the historical use of the word. In ancient Rome, "petere" could also refer to seeking favor or affection, which is closer to the modern meaning of "pet."
Over time, the word evolved to refer to a beloved animal that is often stroked or caressed, hence the connection to seeking affection.