Using JQuery on HTML elements with Ids containing special characters - javascript

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

Related

Using variables with jQuery's replaceWith() method

Ok this one seems pretty simple (and it probably is). I am trying to use jQuery's replace with method but I don't feel like putting all of the html that will be replacing the html on the page into the method itself (its like 60 lines of HTML). So I want to put the html that will be the replacement in a variable named qOneSmall like so
var qOneSmall = qOneSmall.html('..........all the html');
but when I try this I get this error back
Uncaught SyntaxError: Unexpected token ILLEGAL
I don't see any reserved words in there..? Any help would be appreciated.
I think the solution is to only grab the element on the page you're interested in. You say you have like 60 lines. If you know exactly what you want to replace..place just that text in a div with an id='mySpecialText'. Then use jQuery to find and replace just that.
var replacementText = "....all the HTML";
$("#mySpecialText").text(replacementText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mySpecialText">Foo</div>
If you're only looking to replace text then jaj.laney's .text() approach can be used. However, that will not render the string as HTML.
The reason the way you're using .html() is likely illegal is that qSmallOne is not a JQuery object. The method cannot be performed on arbitrary variables. You can set the HTML string to a variable and pass that string to the .html() function like this:
var htmlstring = '<em>emphasis</em> and <strong>strong</strong>';
$('#target').html(htmlstring);
To see the difference between using .html() and .text() you can check out this short fiddle.
Edit after seeing the HTML
So there is a lot going on here. I'm just going to group these things into a list of issues
The HTML Strings
So I actually learned something here. Using the carriage return and tab keys in the HTML string is breaking the string. The illegal-ness is coming from the fact the string is never properly terminated since it thinks it ends at the first line. Strip out the white space in your strings and they're perfectly valid.
Variable Names
Minor thing, you've got a typo in qSmallOne. Be sure to check your spelling especially when working with these giant variables. A little diligence up front will save a bunch of headache later.
Selecting the Right Target
Your targets for the change in content are IDs that are in the strings in your variables and not in the actual DOM. While it looks like you're handling this, I found it rather confusing. I would use one containing element with a static ID and target that instead (that way you don't have to remember why you're handling multiple IDs for one container in the future).
Using replaceWith() and html()
.replaceWith() is used to replace an element with something else. This includes the element that is being targeted, so you need to be very aware of what you're wanting to replace. .html() may be a better way to go since it replaces the content within the target, not including the target itself.
I've made these updates and forked your fiddle here.

Dynamic Unicode Generation into the DOM

I have a function linking to a method for a JavaScript library I'm working on. Basically taking romanized Korean and converting it to specific Unicode sequences and re-inserting it into the DOM. The resulting strings that it generates are correct, but the re-insertion back into the DOM seems off...
For example: If I have the following in my DOM:
<ko>hangug-eo</ko>
The function is meant to convert it accordingly, replacing hangug-eo with 한국어 to show on the browser:
한국어 within the <ko> tags...
The function that does the string setting within the DOM is as follows:
function (){
var z=document.getElementsByTagName('ko');
for(x=z.length;x--;){
z[x].childNodes[0].data=kimchi.go(z[x].childNodes[0].data);
}
}
However, it seems that all this seems to be doing is just placing the &# Unicode entities straight into the DOM without it converting to their respective character equivalents... So all I'm seeing is 한국어
Can anyone please point out what I may be doing wrong?
kimchi.go() is the function that ultimately provides the Unicoded string...
You can always just set the text directly using textContent without having to use HTML entities:
z[x].textContent = '한국어';
But if you need to use HTML entities, just use innerHTML instead
z[x].innerHTML = kimchi.go(z[x].childNodes[0].data);
You can see the latter in the example below.
https://jsfiddle.net/nmL3to8w/1/

Loop though DOM with jQuery to get some data- attribute value

This seems like a simple thing, but I keep getting "undefined"
I am trying out the "data-" HTML5 attribute and I am looping through a bunch of div tags that look like this:
<div id="myEvent"
data-scheduledOn="1399985100000"
data-eventStatus="3">
And I am looping through a bunch of these like this:
$('[id="myEvent"]').each(function(index, divItem) {
alert($(divItem).data("scheduledOn"));
}
But I keep getting "undefined" If I do this (get the attribute) it works fine:
alert($(divItem).attr("data-scheduledOn"));
So What am I missing?
http://api.jquery.com/data/
"The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks."
At least at this point in time, to use the .data function you have to attach the data using the function before you can read it back using the .data function.
If you need to read pre-existing data use the .attr or .prop functions.
It seems as though It is a naming problem as Hamza Kubba suggested, but just a bit different...
if I changed the name of the data attribute to "data-scheduled-on" I can retrieve it by .data("scheduledOn") OR using data-scheduledon and .data("scheduledon") also works.
So don't use CAPS for data- names is the moral of this story!
Please note that per HTML 5 specs, the attribute name should not contain any uppercase letters and some browsers such as FF & Chrome will change any uppercase letter to lowercase. That's why the following demo works if you access the data attributes with lowercase names:
http://jsfiddle.net/fiddleyetu/5LdQd/
$('div.myEvent').each(function(index, divItem) {
console.log($(divItem).data("scheduledon"));
console.log( $(divItem).data("eventstatus") );
});
Ans since you cannot have more than one element on a page with the same ID, I have used a class selector for the demo.
MORAL: Do not use UPPERcase; your browsers may not always be that 'understanding'.

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.

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))

Categories

Resources