From 8f5d87b1b4830e2be7d2bdfb5e21e4a53fd1656e Mon Sep 17 00:00:00 2001 From: "Rick Waldron waldron.rick@gmail.com" Date: Wed, 2 May 2012 12:36:27 -0400 Subject: [PATCH] [#1037] Initial Popcorn.dom, Popcorn.dom.find( selector, context ) implementation Signed-off-by: Rick Waldron waldron.rick@gmail.com --- popcorn.js | 55 +++++++++++++++++++++++++++++++++++++++++++++++++ test/index.html | 8 +++++-- 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/popcorn.js b/popcorn.js index 94523877..ba21e8a8 100644 --- a/popcorn.js +++ b/popcorn.js @@ -1610,6 +1610,61 @@ Popcorn.plugin.effect = Popcorn.effect = Popcorn.compose; + var rnaiveExpr = /^(?:\.|#|\[)/; + + // Basic DOM utilities and helpers API. See #1037 + Popcorn.dom = { + + // Popcorn.dom.find( selector, context ) + // + // Returns the first element that matches the specified selector + // Optionally provide a context element, defaults to `document` + // + // eg. + // Popcorn.dom.find("video") returns the first video element + // Popcorn.dom.find("#foo") returns the first element with `id="foo"` + // Popcorn.dom.find("foo") returns the first element with `id="foo"` + // Note: Popcorn.dom.find("foo") is the only allowed deviation + // from valid querySelector selector syntax + // + // Popcorn.dom.find(".baz") returns the first element with `class="baz"` + // Popcorn.dom.find("[preload]") returns the first element with `preload="..."` + // ... + // See https://developer.mozilla.org/En/DOM/Document.querySelector + // + // + find: function( selector, context ) { + var node = null; + + // Trim leading/trailing whitespace to avoid false negatives + selector = selector.trim(); + + // Default context is the `document` + context = context || document; + + if ( selector ) { + // If the selector does not begin with "#", "." or "[", + // it could be either a nodeName or ID w/o "#" + if ( !rnaiveExpr.test( selector ) ) { + + // Try finding an element that matches by ID first + node = document.getElementById( selector ); + + // If a match was found by ID, return the element + if ( node !== null ) { + return node; + } + } + // Assume no elements have been found yet + // Catch any invalid selector syntax errors and bury them. + try { + node = context.querySelector( selector ); + } catch ( e ) {} + } + return node; + } + }; + // Cache references to reused RegExps var rparams = /\?/, // XHR Setup object diff --git a/test/index.html b/test/index.html index ee8697ad..9de67364 100644 --- a/test/index.html +++ b/test/index.html @@ -27,10 +27,13 @@

    - +
    This should break the tests
    +
    +
    This element will be found when its parent is used as a context
    +
    - +