User:Najevi/sandbox3

jQuery .closest(expr) and .parents(expr) do not behave as advertised when the target element is the DL element
Summary
 * 1)  .closest('dl') will not select a DL element
 * 2) * .closest('dd').parent('dl') will
 * 3) * if a suitable classname has been defined for the DL element then .closest('.classname') WILL NOT
 * 4)  .parents('dl') will not select a DL element
 * 5) * .parents('dd').parent('dl') will
 * 6) * if a suitable classname has been defined for the DL element then .parents('.classname') WILL

JS for these test cases is at http://www.wikia.com/wiki/User:Najevi/global.js

The HTML for the highlighted area of the sidebar in the following 3 screenshots is      Wiki Page failed to load MediaWiki:Widgetwikipage  tidy version:      Wiki Page   failed to load MediaWiki:Widgetwikipage  <dd id="widget_13_editform" class="shadow widget_contents" style="display: none;"/> </dl> In each screen shot the active JS code is visible in the right-hand pane of the window. All previous trials with OK/not OK comments are recorded in the JS source page as comments. If you read those comments then you'll discover that the code I ended up using was .parents('.classname') viz. $( function {   $('#widget_sidebar .WidgetWikiPage i:contains("failed to load")').parents('.WidgetWikiPage').hide; // == PERFECT == });


 * Desired result: can be achieved using a chain of .parent(expr) selectors - tedious but achieves the desired result.


 * Preferred jQuery: If another pair of tags found their way into the hierarchy then the above selection process would fail. Therefore using .closest(expr) seems the most desirable. viz.

It is not obvious that the DL element has not been correctly selected until you compare the above result with this next one:

As you can see the .closest('dl') behaves equivalent to the chain ending in .parent('dd') For some reason the .closest(expr) does not want to select a DL element.

Even though the final code used achieves the job intended I am not understanding why the following selector is not equivalent. $( function {   $('#widget_sidebar .WidgetWikiPage i:contains("failed to load")').parents('dl').hide; });

Best solution so far
Just resigning myself to the fact that .closest('dl') is dysfunctional I tried $( function {   $('#widget_sidebar .WidgetWikiPage i:contains("failed to load")').closest('dd').parent('dl').hide; //  == PERFECT == BEST == }); and this works a charm. I no longer have to concern myself with the possibility of, for example, a pair of B or U tags wrapping my target in another level of hierarchy and breaking the former solution.

If anyone reading this can shed light on why .closest(expr) can select a DL element when a classname is used but not when the DL element/tag name is used then I'd be grateful.