New algorithm for testing elements existence and correct nesting