Consider the following situation: a player for Team A is ruled offside (or, if you prefer, commits a foul on a Team B player). Before the ensuing indirect free kick can be taken, one of the players of Team B has a moment of madness and blatantly kicks the hell out of a player of Team A. Obviously, the Team B player is going to get a red card, but what happens with the ball? Do Team B get to keep the indirect free kick, or is it overridden with a free kick (or penalty kick, if inside the area) in favor of Team A?
Fouls are called only for offences which are committed by a player on the field of play while the ball is in play. (See Interpretations of the Laws of the Game and Guidelines for Referees, page 117.)
If the ball is out of play because the play was stopped by the referee because of a previous offence, no free kick is given, only the persons involved in the misconduct may be cautioned or sent off. So, in your example, the Team B player will be sent off, however, the play will be restarted with the original free kick for Team B.
(Similarly, free kicks are not awarded for misconduct by e.g. a manager, nor for a misconduct of a player outside the field of play. If the referee needs to stop the play because of such misconduct, no team will be given a free kick, and the play will be restarted with a dropped ball at the position of the ball at the time the play was stopped.)