Web

Chrome tips part 1 –selectors

 

Howdy! After some time I’d like to start with some JavaScript stuff.

Today’s browsers give us excellent opportunity to debug our pages with the one and only Web language which is JavaScript. Best example of that tool is Chrome console which gives us more than could be described in any post. As probably each of us knows, the console opens after pressing F12.

image

$$ alias

The most common usage for the console is jQuery programming – we can easily traverse the page searching appropriate element or just testing selectors before scripting. The scenario complicates when there is no jQuery included.

Google Chrome console treats $ as an alias for document.getElementById and the result of such queries are far from the desired outcome. Fortunately there is a nice alternative for it which is “$$” alias.

$$ is alias to document.querySelectorAll function that does pretty similar work as jQuery.find method. So everytime I feel the lack of jQuery I use this thing with success. Remember that it doesn’t implement all the selectors that jQuery has (like :first, :even) for argument/classes queries it is enough.

image

As jQuery.find method replacement we can also use “querySelectorAll” method.

$x alias

Another great tool traversing the document to find some element is $x method. It uses XPath istead of css selectors. It’s good new especially for people who can do more with XPath than with jQuery.

image

How about ability to deal with iframe’s?

$$ and $x does not search for the content of “iframe” element. To do it you have to switch the search context. To do it with $$ once more you have to use the full name of querySelectorAll method but in context of specific “iframe” document:

image

In case of $x it’s is slightly different – you have to pass context as a parameter:

image

You have to remember, that this kind of scripting have to adhere crossframe-scripting policy – domain of the frame should be the same as parent context’s domain.

Advertisements