HTML IDs that start with a number - javascript

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.

Related

Finding a DOM element by attribute name and value using regex

I am trying to find an anchor dom element which has attribute for example, href='/post/3534' by using document.querySelector and regex.
So something like,
document.querySelector("a[href='/post/(/[0-9]+/g)']")
but it obviously does not work.
What is the correct syntax for my purpose ?
I'd appreciate your help.
Selectors don't accept regular expressions - the best you'll be able to do is querySelectorAll the <a>s, and then .find the one whose href matches your condition:
const foundA = Array.prototype.find.call(
document.querySelectorAll('a[href^="/post/"]'),
a => /^\/post\/[0-9]+/.test(a.getAttribute('href'))
);
if (foundA) {
console.log(foundA.getAttribute('href'));
}
foobar
words
numbers

Regex, getElementsByTagName and getElementsByClassName

I call findElements when window.onLoad, with HTML code,
tmp2 selects all tags but the others don't. I really cannot figure out; thanks in advance.
function findElements(){
var tmp = document.getElementsByClassName("*"); // nothing
var tmp2 = document.getElementsByTagName("*"); // all tags, so regexp could be input arg.
var tmp3 = document.getElementsByTagName("b..."); // nothing, but body tag is supposed to be selected
}
The getElementsByTagName method does not accept regular expressions as arguments.
It accepts only strings which must either be:
The wild card *
An exact match for the element type
The getElementsByClassName method does not accept regular expressions.
It accepts only strings which must be:
An exact match for the class name
The querySelectorAll method can use attribute selectors to make more complex matching of attributes (including the class attribute), but even it does not support regular expressions.
If you really want to do a regular expression match, the you would need to select all elements with the wild card (getElementsByTagName("*")) and then loop over the results, testing each one in turn.

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

why jquery id selector not support special character

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/ .

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