Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript retrieve element by it's properties

Every HTML element has offset values. Can I return an element that has, for example, offsetLeft > 10?

Have never heard of this feature, therefore the question.

I'm aware that this can be done with loops, but those are slow. Had an idea about XPath, but cannot find anything related to properties within reference.

Thanks in advance!

P.S. No need for outdated browser compatibility- HTML5'ish can do.

like image 226
tomsseisums Avatar asked Nov 14 '22 17:11

tomsseisums


1 Answers

As far as I'm aware, there is no way to do this that does not involve looping of some form. You could do it in standard JS with something along these lines:

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

Or, if you're using jQuery you can do it with a little less code (but it's probably even slower!):

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

If you think about it, you want to select all of the elements in a document with a certain property value. That's always going to involve a loop at some point, whether you write it yourself or not, as every element has to be checked.

like image 176
James Allardice Avatar answered Dec 15 '22 00:12

James Allardice