I have an element whose id looks like
link-21-'some-text''''sometext'-1.
I have no option to change the id at source. Is there a way to select them using the id?
jQuery("#link-21-'some-text''''sometext'-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-'some-text''''sometext'-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
Related
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.
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/ .
I was adding a class to an element like this:.addClass('middle_item')
Then i notice that class in unique, so i should change it to an id .attr("id", 'middle_item');, right?
So, can I add another id to an element which already has an id?
If the answer is yes, theres any way to get and save the first id in a variable?
Example Fiddle here
No, that is not allowed . . . while there are differences between HTML 4 and HTML 5 in regards to "legal ID values", one of the things that they have in common is that spaces are not allowed in the values:
HTML 4 definition - http://www.w3.org/TR/html4/types.html#type-id
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
HTML 5 definition - http://www.w3.org/TR/html5/dom.html#the-id-attribute
The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
As such, without spaces, you can only ever have a single ID value.
Like #Pointy said, you can only have 1 ID on an element. It seems like you are trying to apply an ID or class to the <li> in order to grab it later? If so, there are better ways of getting at the middle item in a list with jQuery using :nth-child() selector, like in this post. Selector documentation here.
You can only have one id per element see this answer for more details so you have to remove the previous id but that's weird.
All this considered, here is how you could achieve this but I don't imagine that this is actually what you want
$("#listitem1").removeAttr("id").attr("id", "newID")
In the above code I'm chaining the methods by first selecting #listitem1 then removing it's id attribute and finally applying a new id.
Also in your example var i = $("middle_item").attr("id"); returns undefined because the id never applied but if you did you made two errors: first you wrote $("middle_item") when it should have been $("#middle_item") and second because you didn't first remove the previous id.
jQuery Docs
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
I am using JQuery, and I am creating elements dynamically via before() but I am unable to access those elements via ID. It's a bunch of code and I'd rather not post it if possible, but I am checking the text being used as the selector and then checking the length; the length says 0, but I am cross-referencing with the "inspect element" tool in chrome and the ID is most certainly what it should be. Is this a known problem with newly created elements? When I was accessing the element by accessing siblings of a given class it worked just fine, but now there are multiple siblings with the same class and the most efficient way to do things is with an ID.
Here's what I mean when I say I'm checking the text:
alert("id=\"impactPlusMinus~"+questionAnswerNameId+"\"\n"+
$("#impactPlusMinus~"+questionAnswerNameId).length);
The tilde ~ is not a valid character for the id attribute in HTML4. Try using a different character.
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Source: HTML4 specification. http://www.w3.org/TR/html4/types.html#type-id
The HTML5 specification is not so strict on this, but you may run into problems using the tilde on many browsers or frameworks like jQuery. For instance, in jQuery, the tilde in a selector means something else entirely.
You'll need to escape the tilde:
$("#impactPlusMinus\\~"+questionAnswerNameId)
Since you are using reserved keywords in Id, You can access it as an attribute value or escape the special char with \\ if you are directly accessing it.
$('[id="impactPlusMinus~' + questionAnswerNameId+ '"]'
or
$("#impactPlusMinus\\~" + questionAnswerNameId);
from 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: \.
To avoid clashes with how jQuery determines what an identifier looks like, especially in the case of HTML5 which is less strict about naming, you could create the element reference like this:
$(document.getElementById('impactPlusMinus~' + questionAnswerNameId));
This makes sure only the browser is used to find the element, after which the jQuery constructor is applied.
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