diff --git a/src/rules/no-global-selector.js b/src/rules/no-global-selector.js index f11432e6682a6dab37b7bcffe617f3090dc20c48..66724916b56356294125b43b98c7b2d313dac485 100644 --- a/src/rules/no-global-selector.js +++ b/src/rules/no-global-selector.js @@ -13,12 +13,17 @@ module.exports = { docs: { description: 'Disallows global selectors which search the whole document. ' + 'Encourages users to keep references to DOM nodes in memory, instead of selecting them from the DOM each time. ' + - 'Use the `allowIds` option to allow single ID selectors.' + 'Use the `allowBody` option to allow single "body" selectors.' + + 'Use the `allowIds` option to allow single ID selectors.' + + 'The `allowIds` option is ignored if `allowBody` is true.' }, schema: [ { type: 'object', properties: { + allowBody: { + type: 'boolean' + }, allowIds: { type: 'boolean' } @@ -38,13 +43,15 @@ module.exports = { ) { return; } - const value = node.arguments[ 0 ].value; - const allowIds = context.options[ 0 ] && context.options[ 0 ].allowIds; + const { value } = node.arguments[ 0 ]; + const options = context.options[ 0 ] ?? {}; + const { allowBody, allowIds } = options; if ( typeof value !== 'string' || !value || value === '#' || - ( allowIds && idPattern.test( value.trim() ) ) + ( allowBody && /^body$/i.test( value.trim() ) ) || + ( !allowBody && allowIds && idPattern.test( value.trim() ) ) ) { return; } @@ -79,8 +86,19 @@ module.exports = { context.report( { node, - message: 'Avoid queries which search the entire DOM. Keep DOM nodes in memory where possible.' - } ); + message: `Avoid queries which search the entire DOM. Keep DOM nodes in memory where possible.${allowBody ? ` +First, get a "body" reference. Then, use that reference to search. + const $body: JQuery = $( 'body' ); +By a class name: + const $classes: JQuery = $body.find( '.class' ); +By an ID: + const $ids: JQuery = $body.find( '#id' );` : `First, get a "body" reference. Then, use that reference to search. + const $body: JQuery = $( document ).find( 'body' ); +Search a class name: + const $classes: JQuery = $body.find( '.class' ); +Search an ID: + const $ids: JQuery = ${allowIds ? "$( '#id' )" : "$body.find( '#id' )"};`}` + } ); } } ) };