Skip to content

Instantly share code, notes, and snippets.

@weaver
Created October 14, 2010 18:54

Revisions

  1. weaver revised this gist Oct 29, 2010. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions make-selector.js
    Original file line number Diff line number Diff line change
    @@ -8,11 +8,12 @@ function makeSelector(el) {

    for (; el.parentNode; el = el.parentNode) {
    tag = el.tagName;
    el = el.previousSibling;

    for (index = 0; el.previousSibling; el = el.previousSibling)
    for (index = 0; el.previousSibling;) {
    el = el.previousSibling;
    if (tag == el.tagName)
    index += 1;
    }

    stack.unshift(tag + ':eq(' + index + ')');
    }
  2. weaver revised this gist Oct 14, 2010. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions make-selector.js
    Original file line number Diff line number Diff line change
    @@ -33,11 +33,11 @@ function testSelector(query) {
    query = $(query);

    var el = query.get(0),
    selector = makeSelector(query.get(0));
    selector = makeSelector(el);

    console.log('Made selector', selector, 'for', el);

    var probe = $(selector).get(0);
    if (!probe === el)
    console.error('Expected', el, 'not', probe);
    }
    }
  3. weaver created this gist Oct 14, 2010.
    43 changes: 43 additions & 0 deletions make-selector.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    // Create an absolute jQuery selector for a DOM element.
    //
    // + el - Element to select.
    //
    // Returns String selector.
    function makeSelector(el) {
    var tag, index, stack = [];

    for (; el.parentNode; el = el.parentNode) {
    tag = el.tagName;
    el = el.previousSibling;

    for (index = 0; el.previousSibling; el = el.previousSibling)
    if (tag == el.tagName)
    index += 1;

    stack.unshift(tag + ':eq(' + index + ')');
    }

    return stack.join(' > ');
    }

    // Test makeSelector()
    //
    // + query - String, jQuery, or DOM Element
    //
    // Choose the first element in `query` and generate a selector for it.
    // Log this to the console. Report an error if the selector doesn't
    // select the original element.
    //
    // Returns nothing.
    function testSelector(query) {
    query = $(query);

    var el = query.get(0),
    selector = makeSelector(query.get(0));

    console.log('Made selector', selector, 'for', el);

    var probe = $(selector).get(0);
    if (!probe === el)
    console.error('Expected', el, 'not', probe);
    }