removes trailing whitespace
select and deselect will skip invalid elements rather than crashing