The Virginia legislature elected Albert H. Grenadier an Alexandria judge today, but only after 18 House Republicans and an independent cast surprise votes for James M. Thomson, once the House's powerful Democratic leader.

The Republicans said that had the election been held under different rules, their votes -- plus the 33 Thomson had won in a House Democratic caucus -- would have made him the judge. But Thomson's Democratic supporters were bound by caucus rules to support Grenadier, who had defeated Thomson Tuesday by an eight-vote margin in a crucial caucus vote.

Grenadier's election by the General Assembly today ended what had been one of the most bitter and devisive judicial elections in years. Thomson, an Alexandria lawyer and a state delegate for 22 years, had sought a Circuit Court judgeship in the city despite the opposition of the Alexandria Bar Association and civil rights, and feminist groups.

His only support today was in the House, where two Northern Virginia Republicans nominated him. Del. Vincent F. Callahan (R-Fairfax) said that despite past disagreements with Thomson over racial and other issues, he felt that Thomson was a "highly qualified judicial candidate" who got "a raw deal" in th judicial fight. Fairfax Del. Warren E. Barry, who placed Thomson's name before the House, said in an interview that the former Democratic majority leader was "better qualified than Grenadier."

Grenadier, however, received a total of 113 of a possible 140 votes in the overwhelmingly Democratic assembly, to 19 votes for Thomson. The election is for an eight-year term on the bench.