[wp-trac] [WordPress Trac] #34033: Insufficient check for existence of DOM elements in jQuery object

WordPress Trac noreply at wordpress.org
Sat Sep 26 01:00:48 UTC 2015


#34033: Insufficient check for existence of DOM elements in jQuery object
---------------------------+-----------------------------
 Reporter:  tywayne        |      Owner:
     Type:  defect (bug)   |     Status:  new
 Priority:  normal         |  Milestone:  Awaiting Review
Component:  Bundled Theme  |    Version:  trunk
 Severity:  normal         |   Keywords:
  Focuses:  javascript     |
---------------------------+-----------------------------
 This was found in development of Twenty Sixteen
 (https://github.com/WordPress/twentysixteen/issues/294),
 and also exists in Twenty Fifteen, Twenty Fourteen, and Twenty Thirteen.

 It presents itself in slightly different ways in each theme, but the
 essence of the bug is this:

 A variable is set to a jQuery object with something like this ( example
 from twentyfifteen )
 {{{
 secondary = $( '#secondary' );
 button = $( '.site-branding' ).find( '.secondary-toggle' );
 }}}

 And then those variables are used in a conditional statement later like
 this:

 {{{
 if ( ! secondary || ! button ) {
     return;
 }
 }}}

 The conditional check is attempting to return early if the DOM elements
 don't exist, but since the variables contain a jQuery object, they are
 truthy regardless of whether it found any DOM elements.

 A more appropriate check would be to use {{{ .length}}} like so:

 {{{
 if ( ! secondary.length || ! button.length ) {
         return;
 }
 }}}

--
Ticket URL: <https://core.trac.wordpress.org/ticket/34033>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list