Javascript retrieves an element by its properties

Each HTML element has offset values. Is it possible to return an element that has, for example offsetLeft > 10,?

Never heard of this feature, so the question is.

I know this can be done with loops, but they are slow. I had an idea about XPath, but could not find anything related to the properties contained in the link.

Thanks in advance!

PS There is no need for legacy browser compatibility - HTML5 can help.

+5
source share
5 answers

As far as I know, there is no way to do this that is not related to a cycle of any form. You can do this in standard JS with something like this:

var elems = document.getElementsByTagName("*"),
    myElems = [];
for(var i = 0; i < elems.length; i++) {
   if(elems[i].offsetLeft > 10) myElems.push(elems[i]);
}

, jQuery, ( , , !):

var myElems = $("*").filter(function() {
    return $(this).offset().left > 10;
});

, . - , , , .

+4
0

jQuery

<div>Dont find me</div>
<div this="yes">Find me</div>

$('div[this=yes]'); // will select the second div

, , - , , dom upfront. , dom. .

0

I would suggest that the best way to do this is to extend the jQuery selector. Something like this works well:

$.extend($.expr[':'],{

        offsetLeft: function(a,i,m) {
            if(!m[3]||!(/^(<|>|=)\d+$/).test(m[3])) {return false;}
            var offsetLeft = $(a).offset().left;
            return m[3].substr(0,1) === '>' ?
                 offsetLeft > parseInt(m[3].substr(1),10) :
                     m[3].substr(0,1) === '<' ? offsetLeft < parseInt(m[3].substr(1),10) :
                         offsetLeft == parseInt(m[3].substr(1),10);
        }
});

This will allow you to select items using syntax like

$('span:offsetLeft(>10)')

or

$('.someClass:offsetLeft(<10)')

or even

$('.someClass:offsetLeft(=10)')

Real-time example: http://jsfiddle.net/X4CkC/

I must add that this intercepts jQuery selectors, which are usually pretty fast, but there is no doubt somewhere in the depths there is a loop. There is no way to avoid this.

-1
source

You can easily do this with jQuery

$("*").each(function(index, elem){
    if($(this).offset().left > 10){
        // do something here with $(this)
    }
});
-2
source

All Articles