C
C
cat_crash2012-11-17 19:57:54
JavaScript
cat_crash, 2012-11-17 19:57:54

Parse Jquery selector with custom pointers?

Good day.

Maybe I'm reinventing the wheel. If so, please point me to the right path.
The essence of the problem: There is a Jquery selector, but not a standard one, but supplemented with certain things so that you can select attribute values, for example:
div.border_premium [email protected]
I use the function to turn it into a query of the form

$('div.border_premium a').each(function(){<br>
var return = $(this).attr('href');<br>
});<br>

But the "transformation" algorithm is very noticeable and does not allow to analyze selectors where there is more than one custom "crutch" because making it normal now
if (path.match(/'@"/i)) {<br>
  var path=....<br>
}<br>


What I would like: so that you can parse complex selectors in the form
div.listItem|table tr td:eq(0)~contents().eq(0).text()
- in the transformed form should become
$('div.listItem').find('table tr td:eq(0)').each(function (){<br>
var return = $(this).contents().eq(0).text();<br>
});<br>


Actually the question: give me an idea how to consistently compose the correct "parsers" of strings so that you can incrementally increase the selectors

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
creage, 2012-11-17
@creage

I wouldn't do that at all - you're putting custom logic on top of "standard" jQuery selectors, filling your code with untold risks. How will the next / new developer deal with all this? What will you do if something is changed/added in Sizzle and it breaks everything for you?
But everything, probably, depends on tasks.
If you need to select certain attributes of a collection of elements, write a wrapper, something like

function collectAttributes(collection, attribute){
    // тут собираете запрашиваемые атрибуты и возвращаете новую коллекцию
}

and just set this function where necessary. The same goes for the rest of the selectors. If you need
$('div.listItem').find('table tr td:eq(0)').each(function (){
     var return = $(this).contents().eq(0).text();
});

then write like that, and not horror from div.listItem|table tr td:eq(0)~contents().eq(0).text().
PS I also recommend using each2 instead of each - it affects performance quite a lot .
$.fn.extend({
  /*
  * 4-10 times faster .each replacement
  */
  each2 : function (c) {
    var j = $([0]), i = -1, l = this.length;
    while (
      ++i < l
      && (j.context = j[0] = this[i])
      && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
    );
    return this;
  }
});

D
denver, 2012-11-17
@denver

For example, we do selector.split('~') first - we get 1..2 elements, we save the second (if any) for later, and we do split("|") for the first, we get 1..∞ more elements, the last of we do split('@'), voila, all parsed without any checks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question