views:

71

answers:

2

Hi again!

First of all, after "testing" a while I have to say, stackoverflow is really really cool!

To my question: I want to check if $(this) has not any parents that have a class or id specified in an js-array.

By now I did this with "eval", but Andy E. just convinced me, that it is better to abandon "eval". However I have no clue how to do it in this case.

Here is pretty much of what I did:

var testthis = '!(($(this).parents("'+<MY_ARRAY>.join('").length > 0 || $(this).parents("')+'").length > 0)';
if (eval(testthis)) {
    ....
}

If anybody is kind enough to answer my question, I have to appologize that I cannot read (and comment or rate) his/her answer in the next few hours. Sorry!

+2  A: 

Try this, no eval needed:

if(!$(this).parents(<MY_ARRAY>.join(', ')).length) {
 //elem has none of those parents
}

MY_ARRY in this case contains things like ".class1", ".class2", "#id1", "#id2"

Alternatively slower but yo can check for both cases if the array is just strings:

if(!$(this).parents("." + <MY_ARRAY>.join(', .')).length &&
   !$(this).parents("#" + <MY_ARRAY>.join(', #')).length) {
 //elem has none of those parents
}

MY_ARRY in this case contains things like "class1", "class2", "id1", "id2", but IDs could match like #class1 could be a match, so this is less desirable.

Nick Craver
Why are you adding quotes to the selector? Assuming the elements of the array already are prepended with "#" or "." as appropriate, it should just be `theArray.join(', ')`. That'll be a string, and a string is what a selector is.
Pointy
@Pointy - I get what you mean now, shortened above, thanks!
Nick Craver
thanks for your answer! It seems to be great, however I didn't have the possibility to test it yet. I will mark your answer as accepted as soon as I test it. Thank you!
Marcel
thank you! works like a charm!
Marcel
A: 

Well you could iterate through the nodes for $(this) assuming there are more than one, check the parents by walking up the tree to each one, caching any paths you have already walked up, but really I think whatever you are trying to do here, there's probably a better way.

apphacker