What does $$ mean in Javascript? - javascript

I am looking at some javascript code and it has this in a function:
$$('.CssClass').each(function(x) { .... } )
I get that the intent is to apply the anonymous function to each element with a class of CssClass, but I can't work what the $$ refers to ... and can't google for $$!
Update: thanks for the hints. The javascript comes from the iPhone look-alike library: jPint which includes the prototypejs library, and does define $$ as:
function $$() {
return Selector.findChildElements(document, $A(arguments));
}

Probably this prototype function:
$$(cssRule...) -> [HTMLElement...]
Takes an arbitrary number of CSS
selectors (strings) and returns a
document-order array of extended DOM
elements that match any of them.
http://www.prototypejs.org/api/utility#method-$$

$ is an ordinary symbol character, thus "$", "$$", "$$$" are ordinary variables.
the meaning of $ depends upon the libraries that are in use; in jQuery the $-function creates a jquery object from a css selector, e.g. $("DIV") is a collection of all DIVs in the current document.

Are you looking at a library such as mootools by chance? This is used as a short-hand to certain types of objects by accessing the DOM. They do things like $('myElement') to access page elements for example.

$ is a valid function name in javascript. So something defines a function $$ that takes a string looking for some class called .CssClass and returns a object where you call each on.
I know that jQuery defines a function called $ at least that does similar things.

Any chance you are looking at a MooTools script?
http://www.consideropen.com/blog/2008/08/30-days-of-mootools-12-tutorials-day-2-selectors/ (now owned by a domain grabber)
"The $$ lets you quickly select multiple elements and places them into an array (a type of list that lets you manipulate, retrieve, and reorder the list in all sorts of ways). You can select elements by name (such as div, a, img) or an ID, and you can even mix and match."

Most likely a shorthand function name that handles the DOM accessing of the specified arguments, whether tag name or object id.
As per above, you're likely in MooTools or jQuery.

In the browser's console, it is another way to write querySelectorAll().
Simply selects all the elements on the web page that you need and puts them in an array.
Practical examples:
Select all the elements and set an outline guide for debugging layouts [source]:
$$('*').map((A,B)=>A.style.outline=`1px solid hsl(${B*B},99%,50%`)
Print the image addresses for all the images on a webpage [source]
$$('img').forEach(img => console.log(img.src))

Related

Using JQuery on HTML elements with Ids containing special characters

Problem: using JQuery on HTML elements with Ids containing special characters.
Any special characters can be present anywhere within the Id. In 90% of the cases those are going to be spaces, full stops and dashes.
I think I found a Possible solution but can’t find any documentation that would support this.
Let’s say sElementId is an html element Id that has special characters in it.
Using the following syntax doesn’t work:
$('#'+sElementId).addClass("pointer");
but adding a pair of square brackets works like a charm:
$(['#'+sElementId]).addClass("pointer");
My question is. Is this the correct use of square brackets inside the selector?
Actually, it doesn't work, and does something you didn't expect.
From jQuery documentation:
jQuery( object )
object
Type: PlainObject
A plain object to wrap in a jQuery object.
So if you call $(["#a b"]) (or just $(["a"])) you'll get a jQuery wrapper object for that array-of-string. It looks like a typical jQuery selector object, but it isn't. addClass has no effect on that object.
$([1]).addClass("pointer") // no operation
To select the object, just use $(document.getElementById("a b")) ($() to convert it to a jQuery object).
Alternatively:
if there are multiple elements with the same id (note that this is invalid): javascript - Get multiple elements by Id - Stack Overflow
escape the id to use $(String.raw`#a\ b`) (or equivalently $("#a\\ b")): https://stackoverflow.com/a/4823616/5267751

Changing inner text value of tab through javascript

I'm learning Javascript right now, and attempting to change the text title of a particular tab. It's actually part of a larger Shiny dashboard project, but I want to add some custom functionality to a few tabs. Below are the tabs in question:
Simple enough. I first access my tabs in my Javascript file:
var tabScrub2 = $(document).find('[data-value="scrubTab2"]');
console.log(tabScrub2);
When I use Firefox's developer console, I see that the tab is an object:
Moreover, it looks like I need to change the innerText property of 0, whatever this is, since that corresponds to the title of my tab (the innerText of 1 corresponds to the text inside scrubTab2). However, I'm not familiar with the actual object type being returned here:
Simply put, how the heck do I access and manipulate properties from this? And am I actually accessing an array? When I type in
var scrub2 = tabScrub2["1"];
console.log(scrub2);
I get an HTML element. I'm seen the a element in CSS and jQuery, but am not super familiar with how to manipulate its properties programmatically? How do I go about accessing and manipulating the innerText properties of this via Javascript? For instance, how would I hide scrubTab2, or change its title to something else?
The first object you're seeing is jQuery's wrapper around the real DOM elements. It's not an actual array, but it does contain all of the elements that matched your query under zero-indexed properties (e.g. "0" and "1") which allows you to access to them via an array-like API (e.g. tabScrub[1]).
Your method of grabbing a node using tabScrub2["1"] is correct (see this question in the jQuery FAQ). It's more likely to see that done with a numeric key though (i.e. tabScrub[1]) because that matches the way you would access an element in a normal array.
As far as manipulating properties of the DOM node, the DOM's API is notoriously inconsistent and quirky (hence the need for things like jQuery in the first place). However, for your use case you can just assign a string to the innerText property directly (e.g. tagScrub2[1].innerText = "Tab title"). MDN is a great resource if you're looking for reference material on other parts of the DOM.
A side note: if you're looking for a specific element you should use a query that will only match that element. It's generally a bad sign if you're grabbing extra elements and then accessing the element you want at a key other than 0. If you're doing this then your code depends on other (potentially unrelated) nodes in the DOM existing before your node, and if/when you change those nodes your original code will break.
Just use jQuery eq method to get the relevant object index from the array.
For an example
//Query and get first element.
var tabScrub2 = $(document).find('[data-value="scrubTab2"]:eq(0)');
//Hide
tabScrub2.hide();
//Change title
tabScrub2.attr("title", "New Title Text");
Lean more about jQuery eq here.
https://api.jquery.com/eq/
Since you use jquery selectors tabScrub2[0] returns the native DOM element instead of another jQuery object. Therefore the hide function won't work in that object since the native DOM element doesn't implement such type of functionality for an element. That's why you have to use jQuery pseudo selector as above. Because hide will only work with a jQuery object.

What does $($(this)) mean?

I saw some code around the web that uses the following statement
if ($($(this)).hasClass("footer_default")) {
$('#abc')
.appendTo($(this))
.toolbar({position: "fixed"});
}
What is the use of $($(this)) and why is that necessary here?
Yes, $($(this)) is the same as $(this), the jQuery() or $() function is wonderfully idempotent. There is no reason for that particular construction (double wrapping of this), however, something I use as a shortcut for grabbing the first element only from a group, which involves similar double wrapping, is
$($('selector')[0])
Which amounts to, grab every element that matches selector, (which returns a jQuery object), then use [0] to grab the first one on the list (which returns a DOM object), then wrap it in $() again to turn it back into a jQuery object, which this time only contains a single element instead of a collection. It is roughly equivalent to
document.querySelectorAll('selector')[0];, which is pretty much
document.querySelector('selector');
You can wrap $ as many times as you want, it won't change anything.
If foo is a DOM element, $(foo) will return the corresponding jQuery object.
If foo is a jQuery object, $(foo) will return the same object.
That's why $($(this)) will return exactly the same as $(this).
There is no specific need for double-wrapping and $($(this)) is exactly the same as $(this).
That said, I once found this double-wrapping in one file in my project, committed by another developer. Tracking the changes through revision, turned out that it started as $($(this).find('selector').first()) - that is, the result of some selector was wrapped to create a new object. Then for whatever reasons, the selector was removed and only the double-wrapping of this remained. Needless to say, on the next commit it was changed to $(this).
As explained before me, $($(this)) and $(this) are absolutely identical. jQuery returns the same jQuery object if you try to wrap it more than once.
Additionally, for performance considerations it is a good practice to reuse jQuery objects - it is quite expensive to create jQuery objects, especially the ones with complex selectors. Example:
var $this = $(this);
if ($this.hasClass("footer_default")) {
$('#abc')
.appendTo($this)
.toolbar({position: "fixed"});
}
Just google for 'jQuery best practices' - it will take a 30 min for you to learn these basics and you will use jQuery way more effectively.
There is no meainig of doing that.
The following code return the same:
console.log($($(this)).hasClass("footer_default"))
console.log($(this).hasClass("footer_default"))
a boolean value depenging on if the selected element has or not the class footer_default:
.hasClass( className )Returns: Boolean
Demo: http://jsfiddle.net/IrvinDominin/aSzFn/
$(this) and $($(this)) both return jquery object.
There is no difference between these two.

JQuery: What's the difference between referencing an element using #[objectId] or [id=objectId]

Can anybody tell me what's the difference between referencing an element using #[objectId] or [id=objectId]?
The first one is very fast, as jQuery internally uses getElementById when it recognizes the pattern (using a regular expression).
The second one asks jQuery to iterate over all objects having an id. It's very slow. jQuery doesn't even stop iterating when it find one match in that case.
The only legitimate reason to use a [id... selector is when you don't just search by an exact id, for example you might want to search all elements whose id starts with "something" using $('[id^=something]').
Assuming you have a valid HTML (no reused id) and a valid id, you can still have problems with $('#'+someId) (for example when your id contains a quote, or anything that breaks Sizzle's pattern recognition system). In that case, use $(document.getElementById(someId)).
Following your comment : Yes, a "#" in an ID makes it impossible for Sizzle (jQuery's selector engine) to understand your selector. Sizzle uses the following regex :
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
and /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/.test('#som#thing') returns false.

How to tell the type of a JavaScript and/or jQueryobject

This question pertains as much to the ECMAScript language implementation we know as JavaScript as it does to jQuery and the developer tools availble in most popular browsers.
When you execute a statement like so:
var theElement = $('#theId').closest();
what is the type of theElement?
I assume that in a jQuery situation like above, many jQuery methods including the one above actually return the jQuery object itself, which packages the stuff you actually want to get to. This, so that it may maintain a fluent API and let you join method calls in a single statement like so:
$('#selector').foo().bar().gar().har();
However, in the case of jQuery then, how do you determine what the real underlying type is? For example, if the element returned was a table row with the Id tableRowNumber25, how do you get to that, say, using FireBug.
When I look at either a jQuery returned object or a simple JavaScript object in the watches window of Firebug or any of the Developer Tools in most popular browsers, I see a long laundry list of properties/keys and I don't know which one to look at. In a jQuery object, most of the properties are lamdas.
So, really, my question is -- how do you know the underlying type, how do you know what's actually being returned?
The type of theElement will be [object jQuery].
If you want the HTML element itself, you have to select it:
console.log(theElement[0]) //Return <div id='theId'>
console.log(theElement.get(0)) //Return <div id='theId'>
If you want the node name, there is a property in the HTML node element call nodeName wich return the capitalised node name:
console.log(theElement[0].nodeName)// Return DIV
typeof(jQueryElementList.get(0)) will return a string of the type.
Some browsers might return this as upper or lower case, I think. IE probably uppercases (see Testing the type of a DOM element in JavaScript). Apparently you can check the nodeType attribute (jQueryElementList.get(0).nodeType) to determine whether it is an html object/tag.

Categories

Resources