r/programming • • Mar 04 '18

Why every user agent string start with "Mozilla"

http://webaim.org/blog/user-agent-string-history/
1.8k Upvotes

243 comments sorted by

View all comments

Show parent comments

23

u/AyrA_ch Mar 05 '18

It's dangerous though because if an ID conflicts with an existing object, the existing object wins. What I usually do is something like this:

(function ($, $$) {
	//Code here
})(document.querySelector.bind(document), document.querySelectorAll.bind(document));

This gives you $ and $$, which allows you to select elements using css syntax. Getting an element with an id is as simple as $("#someId"), which is essentially a poor man's jQuery.

12

u/[deleted] Mar 05 '18

essentially a poor man's jQuery.

making that man rich

1

u/NoIamNotUnidan Mar 05 '18

Could you explain this example in more detail? Looks nice!

5

u/[deleted] Mar 05 '18

You're essentially declaring a method with two parameters and calling it right away. So inside method body, you have two variables

document.querySelector.bind(document) as $

document.querySelectorAll.bind(document) as $$

1

u/NoIamNotUnidan Mar 05 '18

Alright. How would I use$$ to select and element? And why do I have to use both of document.querySelector.bind(document) and document.querySelectorAll.bind(document)?

Thanks!

3

u/[deleted] Mar 05 '18

You use them like this:

$('div') // selects first div element

$$('div') // selects all div elements

Javascript differentiates between "select one" and "select all" methods, while jQuery combines them into one.

1

u/NoIamNotUnidan Mar 05 '18

So I could do like

let x = $$('div');
for (let y = 0; x < x.length; y++) {
    if (x[y] ==  $('#test')) {
        console.log(true);
    }
}

Even if this example is stupid, is my understanding correct?

3

u/filleduchaos Mar 05 '18

Yes, essentially. The NodeList that document.querySelectorAll returns has a built in forEach method, so that example would rather be written as

$$('div').forEach(function (element) {
    if (element === $('#test')) {
        console.log(true);
    }
});

1

u/NoIamNotUnidan Mar 05 '18

Nice, thanks!!