Javascript confusion - javascript

var allRapidSpells = $$('input[value^=RSW]');
Can anyone tell me what that does?

I would venture to guess that you're using MooTools, a JavaScript framework. The $$() function is used to select an element (or multiple elements) in the DOM.
More specifically, the $$('input[value^=RSW]'); syntax is selecting all input elements whose value attribute starts with RSW.
Other attribute selectors include:
= : is equal to
*= : contains
^= : starts-with
$= : ends-with
!= : is not equal to
~= : contained in a space separated list
|= : contained in a '-' separated list
Edit: It looks as though Prototype, another JavaScript framework, uses the same syntax.

Return all inputs that hava value starting with RSW

It calls the function named '$$' with the parameter 'input[value...' and assigns the returnvalue of that function to the var allRapidSpells.
Javascript doesn't consider the '$' to be a reserved character, which jQuery makes excellent use of.

It looks like it uses some CSS selectors using some javascript library, the CSS selectors return all input tags where the value begins RSW.

calls a method on the windows object called $$ and passes a string argument to it, which appears to be an xpath expression.
which returns input tags that contain an attribute called value starting with RSW.

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

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.

Array check element ID with wildcard in if statement

I can check an object ID in a array with
if (obj[0].id != "myID")
I would like to do the same with a wildcard, so that
if (obj[0].id != "myID*")
will exclude #myID1, #myID2, #myID3 etc.
I have to stay inside the if statement for this check, I can't call an external function.
If it is not possible, I can use obj[0].className instead of .id :
if (obj[0].className != "myClass")
but every object has several classes in addition of myClass.
jQuery is allowed although I'm not sure it will help.
If you're using jQuery (you've added the tag), why not use the selectors?
$('*:not[id^="myID"]')
This gets all the elements where the attribute does not start with myID. You can use this in your if statement like so:
if($(obj[0]).is('[id^="myID"]'))
First of all, you can definitely use an id attribute selector like this
if(!$(obj[0]).is("[id^=myID]"))
However, why not assign a class to all those elements instead? That sounds like a much more reasonable approach, allowing
if(!$(obj[0]).hasClass("myClass"))
Using String.prototype.indexOf might be one possible approach:
if (obj[0].id.indexOf('myID') !== 0) {
// ID does not start with 'myID'
}
You can even use regular expressions:
if( !/(myId)/g.test( obj[0].id.indexOf('myID') ) ) {
}
I can suggest you this really good playground to test you regexp:
http://lea.verou.me/regexplained/
And this talk:
http://www.youtube.com/watch?v=EkluES9Rvak
Regular expression can be very powerful. Maybe your case is not that hard to be managed with other tecniques but you would find regular expressions reeeally useful in the future for other problems.
You could check that the first 4 characters are myID with .substring():
if(obj[0].id.substring(0,4) != 'myId'){ }
If you wanted to use jQuery it would be really easy to check the id or class:
if(!$(obj[0]).is('[id^=myId]')){ }
or
if(!$(obj[0]).hasClass('myClass')){ }

What does $$ mean in 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))

Parsing XML with namespaces using jQuery $().find

I'm trying to get the contents of a XML document element, but the element has a colon in it's name.
This line works for every element but the ones with a colon in the name:
$(this).find("geo:lat").text();
I assume that the colon needs escaping. How do I fix this?
Use a backslash, which itself should be escaped so JavaScript doesn't eat it:
$(this).find("geo\\:lat").text();
That isn't just an ordinary element name. That's a qualified name, meaning that it is a name that specifically refers to an element type within a namespace. The element type name is 'lat', and the namespace prefix is 'geo'.
Right now, jQuery can't deal with namespaces very well, see bug 155 for details.
Right now, as a workaround, you should be able to select these elements with just the local name:
$(this).find("lat").text();
If you have to distinguish between element types with the same local name, then you can use filter():
var NS = "http://example.com/whatever-the-namespace-is-for-geo";
$(this).find("lat").filter(function() { return this.namespaceURI == NS; }).text();
Edit: my mistake, I was under the impression that patch had already landed. Use Adam's suggestion for the selector, and filter() if you need the namespacing too:
var NS = "http://example.com/whatever-the-namespace-is-for-geo";
$(this).find("geo\\:lat").filter(function() { return this.namespaceURI == NS; }).text();
if you have a jquery selector problem with chrome or webkit not selecting it try
$(this).find('[nodeName=geo:lat]').text();
this way it works in all browsers

Categories

Resources