why jquery id selector not support special character - javascript

when using the special character to find the element like as below $("#search#") the exception will occur. how to resolve it?
I've tried using the all special character but it's working with * character like $("#search*") without any error, but others #$%^&() throw an error.So why it accepts the * character but why the other character doesn't.

If you have special character for ids, you should escape them using \\ (two backslashes) when you access them. But as far as I know this will only be allowed with html5.
As stated in jquery selector documentation
To use any of the meta-characters ( such as
!"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must
be escaped with with two backslashes: \. For example, an element with
id="foo.bar", can use the selector $("#foo\.bar").
alert($("#search\\$").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="search$">Heh</div>

Try utilizing Attribute Equals Selector [name="value"]
$("[id='search#']").click(function() {
$(this).html(this.id)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="search#">click</div>

Many special characters are not allowed (Which characters are valid in CSS class names/selectors?).
A way to still select what you want, by looking for all but the special character(s) be seeing what some at the start, end, or contained somewhere within the tag's id.
Starts with: jQuery ID starts with
$('[id^="start-with"]')
Ends with: jQuery Selector: Id Ends With?
$('[id$="ending-part"]')
Contained somewhere within: jQuery ID Contains
$('[id*="any-spot-at-all"]')
There are others ways to "skin the cat" of course - some other selector options for example, to find only a part of a id or class or any other HTML tag attribute can be found at http://api.jquery.com/category/selectors/attribute-selectors/ .

Related

HTML IDs that start with a number

I generate GUIDs for id's in my HTML like
<div id="9121c01e-888c-4250-922f-cf20bcc7d63f">...</div>
According to HTML5 specs, this is valid. However, if you try to find such a element with document.querySelector or document.querySelectorAll, you'll get an error saying that the selector is invalid.
I know that for CSS rules, such an ID is not valid. Does the querySelector methods of 'document' rely on CSS?
Does the querySelector methods of 'document' rely on CSS?
The strings you pass querySelector and querySelectorAll are CSS selectors. So yes, they follow the rules of CSS selectors, one of which (as you mentioned) is that an ID selector cannot start with an unescaped digit. So they don't rely on CSS per se, but they follow the syntax of CSS selectors.
You can select that element either by escaping the first digit (which is fairly ugly*):
var e = document.querySelector("#\\39 121c01e-888c-4250-922f-cf20bcc7d63f");
...or by using an attribute selector:
var e = document.querySelector("[id='121c01e-888c-4250-922f-cf20bcc7d63f']");
Example:
document.querySelector("#\\39 121c01e-888c-4250-922f-cf20bcc7d63f").innerHTML = "Yes!";
document.querySelector("[id='9121c01e-888c-4250-922f-cf20bcc7d63f']").style.color = "green";
<div id="9121c01e-888c-4250-922f-cf20bcc7d63f">...</div>
Of course, if you're just getting the element by its ID and not using a compound selector starting with an ID, just use getElementById, which doesn't use a CSS selector, just the ID value as plain text:
var e = document.getElementById("9121c01e-888c-4250-922f-cf20bcc7d63f");
You only need the other form if you're using a compound selector ("#\\39 121c01e-888c-4250-922f-cf20bcc7d63f > span a"), or passing a selector string into something you don't have control over that you know will use querySelector.
* In a CSS selector, \ followed by up to six hex characters (plus a space if you don't use all six) specifies a character code in hex. 0x39 is the character code for the digit 9. And of course, we had to escape the \ in the string literal since otherwise it would have been consumed by the string literal.
Yes, they use CSS selectors
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
Syntax
element = document.querySelector(selectors);
where
element is an Element object.
selectors is a string containing one or more CSS selectors separated by commas.
But as you append the GUID as ids you can use document.getElementById();
It supports this case.

Select an item that has id that contains &apos;

I have an element whose id looks like
link-21-&apos;some-text&apos;&apos;&apos;&apos;sometext&apos;-1.
I have no option to change the id at source. Is there a way to select them using the id?
jQuery("#link-21-&apos;some-text&apos;&apos;&apos;&apos;sometext&apos;-1") is throwing an error for obvious reasons. Are there any work around for this ?
Since it contains some special meaning character use attribute equals selector or escapes the special meaning character.
Check jQuery selctor docs :
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar").The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.
So it can be like following or escape each meta-character.
jQuery('[id="link-21-&apos;some-text&apos;&apos;&apos;&apos;sometext&apos;-1"]')
This should work
$('[id*="&apos"]')
select elements which all have &apos in their ID
Use you generic server side language to generate a simple id
use the proper jquery selector to select that element $('#link-21')
assuming you data in the db is properly formatted you should have a unique primary key, use that unique key to form your unique id

Use a dot in a class name within jquery: $('.B.Avf').toggle();

Is it possible to use a dot in a classname inside Jquery?
$('.B.Avf').toggle();
I need to keep the dot in: B.Avf classname.
Can i somehow escape it?
Is this possible?
UPDATE
I tried to escape it with "\" with no success.
You can always just use the [attr="val"] selector for this.
$('[class*="B.Avf"]')
The *= means "class contains...". Since this is looking at the attribute directly and there could be more than one class, you don't want to use =.
There are two ways to select elements that have special selection characters in their identifiers. As Tushar mentioned in a comment, you can use a double backslash (\\) to escape the special character in query (including both jQuery and document.querySelector), or you can use an attribute selector, as Rocket Hazmat pointed out.
Note that in CSS (that is, an actual stylesheet, not JavaScript), the selector is slightly different. You only need a single backslash to escape the special characters.
Demo below:
// use a double backslash to escape characters in JavaScript query selectors
document.querySelector(".a\\.b").style.backgroundColor = "blue";
//or use an attribute selector!
document.querySelector('[class="a.b"]').style.color = "white";
/* Use a single backslash to escape characters in CSS */
.a\.b{border:1px solid black;}
<div class="a.b">My class name is a.b</div>

jQuery eq function unexpected behavior

I found a bug in a program I had written, but the behavior of the error is inexplicable to me:
If I have:
<input type="text" name="cust_id" value="666" />
<input type="text" name="phone[]" value="666" />
And then use this selector:
var test = $("input[name=phone[]]:eq(0)");
test.css("color", "red");
I see this:
What I'm surprised by is the fact that the eq(0) selects the first input even though I explicitly tell it to find only ones with name=phone[]
Here is a fiddle: https://jsfiddle.net/1xdnv1t8/
Is this expected behavior? Does the eq selector ignore attribute selectors?
You need to quote name attribute:
var test = $("input[name='phone[]']:eq(0)");
because phone[] is not valid name without quotes. So jQuery parser (or DOM) simply ignores everything invalid and treats selector as if it was simply input[name='phone']:eq(0). Also worth noting, that looks like this behaviour is fixed in more up to date versions of jQuery. You use pretty old 1.6.4 in your demo, but if you check it with 1.8.x and above it will work properly throwing error.
For example, if you try
try {
document.querySelector("input[name=phone[]]")
}
catch(e) {
alert(e.message)
}
it will even throw an error
Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': 'input[name=phone[]]' is not a valid selector.
But jQuery is more forgiving and it just selects whatever it can.
Use
var test = $("input[name='phone[]']:eq(0)");
JSFiddle
In the selector especification states
jQuery( "[attribute='value']" )
attribute: An attribute name.
value: An attribute value. Can be either an unquoted single word or a quoted string.
You are missing quotes around the attribute value. Try this -
var test = $('input[name="phone[]"]:eq(0)');
The square brackets in your selector confuse the attribute selection part as it is not quoted. Notice if you change the name of the second input to phone then it works as expected:
$("input[name=phone]:eq(0)")
Alternatively, wrap the attribute selector in quotes:
$("input[name='phone']:eq(0)")
While quoting the name attribute's value isn't strictly required (jQuery for the most part will work fine without them), as you noticed you can run into unusual situations when there are non-alphanumeric characters involved and jQuery interprets them as CSS notation.
The solution is to always properly escape any of these characters (:, ., [, ], etc.) as jQuery recommends, with two backslashes:
In order to tell jQuery to treat these characters literally rather
than as CSS notation, they must be "escaped" by placing two
backslashes in front of them.
So according to the jQuery documentation, you should be using var test = $("input[name='phone\\[\\]']:eq(0)"); as the selector (although simply properly quoting the string in your case will also work fine).
jsFiddle example
Ref: How do I select an element by an ID that has characters used in CSS notation?

Tilde in jQuery selector

My understanding of the tilde's function in Javascript is that it performs a bitwise not operation (i.e. 1 becomes 0 and vice versa; 1000 becomes 0111). However, I've recently begun work on an existing project where my predecessor has included a lot of code like this:
var iValuation = $('div[class~="iValuation"]');
Can anyone tell me what the purpose of the tilde in this instance is? I've not come across it before and haven't been able to find any reference to it online.
Tiled used as selector means
Selects elements that have the specified attribute with a value
containing a given word, delimited by spaces.
which is not a JavaScript operator at all.
More from doc:
This selector matches the test string against each word in the
attribute value, where a "word" is defined as a string delimited by
whitespace. The selector matches if the test string is exactly equal
to any of the words.
For example:
<input name="man-news" />
<input name="milk man" />
<input name="letterman2" />
<input name="newmilk" />
$('input[name~="man"]') will select only second input, because its attribute name is separated by space.
For detail see here
That isn't a JavaScript operator. It appears in a string.
Since that string is passed to the jQuery function, and it doesn't look like a piece of HTML, it is a selector.
Specifically one of the attribute selectors:
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces). Also if "val" is the empty string, it will never represent anything.
$ is the jQuery selector function, which contains a CSS3 Selector String: According to the CSS3 Selector Definition, the selector you encountered selects:
E[foo~="bar"] an E element whose "foo" attribute value is a list of whitespace-separated values, one of which is exactly equal to "bar"
in the DOM. Because the Tilde is wrapped in a string, it is not working as an operator.
In case you're wondering about the difference between
[class~="foo"]
and
[class*="foo"]
~ will match only with whitespace around (e.g. 'foo bar' but not 'foo-1')
* will match with or without whitespace around (e.g. 'foo bar' and 'foo-1')
~ - Attribute Spaced Selector
* - Attribute Contains Selector

Categories