Getting dynamically created element by ID (Jquery) - javascript

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.

Related

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

Is it possible add an id to an element which already has an id

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.

Problem with at sign in div name

I have a page which has some divs. Each div id starts with the word divfor and have a suffix after that. Like divforjohn, divforjim ... etc. These suffixes come from database.
My problem is when i try to load something in that div it creates problem if it have the # sign in it. So, if I do something like below:
$("#divfor"+divsuffix).html('some text goes here.');
then it doesnot make any problem if the divname is divforjohn but doesnot work if the divname is divforjohn#x.
So, how can I address a div that has #sign in its id? or its a limitation/bug of jquery?
Thx.
To target the element with id="divforjohn#x" in JavaScript (be it through document.querySelectorAll or through jQuery/Sizzle) you’ll need to escape the #, like this:
$('#divforjohn\\#x')
Demo: http://jsfiddle.net/mathias/nafmt/
Also, the accepted answer is wrong — it states the ID naming rules that were included in the HTML 4 spec. The thing is, browsers never implemented this, so in HTML5 these rules aren’t as restrictive anymore. See “The id attribute just got more classy in HTML5”.
It’s perfectly safe to use weird characters in values for id or class attributes as long as you know what you’re doing.
actually your ID can not contain # as #Peter describes, once u changed your id then u can use like this
There is regex selector for jQuery:
http://james.padolsey.com/javascript/regex-selector-for-jquery/
That is used like this:
$(':regex(id,/^divfor.*/)');
This code works :
var d = document.getElementById("divforjohn#x");
$(d).html('some text goes here.');
jsFiddle example
Update:
As mentioned in the comment, at a point when your only aim is to support HTML5 browsers, by all mean use anything unique and contain at least 1 character for your ID attributes.
See this Stackoverflow thread for further discussion.
Hi, I hope this part of the document is helpful for you:
6 Basic HTML data types - IDs and Names
This is not a bug of jquery/javascript etc.
You can check the more formal HTML4 RFC of course.
Is there any reason you must have # inside the id of an element?
I suggest you should try to avoid it because some legacy browsers aimed to support html4 might not have implemented it this way, as
It might be doing similar to this. I would suggest just base 64'n the string before putting it in the div, then using the base64 name for everything. Or a row id, something generic, that you can always predict the outcome.
You should follow the ID naming rules:
Must begin with a letter A-Z or a-z
Can be followed by: letters (A-Za-z),
digits (0-9), hyphens ("-"),
underscores ("_"), colons (":"), and
periods (".")
Values are case-sensitive

Do browsers widely support numeric quotes in attributes?

There exist other ways of linking to JS, apart from this (the usual)..
<script src="myscript.js" type="text/javascript"></script>
...that utilize other quote types:
<script src="myscript.js" type="text/javascript"></script>
Are these widely supported in modern browsers, and older browsers in use, such as IE6? Basically is it safe to use this method, just as you would use the regular double-quote method?
Edit: The HTML4 spec seems to allow it, but is it well supported in practical reality?
3.2.2 Attributes
Authors may also use numeric character references to represent
double quotes (") and single quotes (').
For double quotes authors can also use the
character entity reference ".
Using " instead of " is simply wrong, it doesn't have the same meaning within the SGML and XML specifications. Argument values of elements should use either single (') or double quotes ("). In the old SGML specification this element
<foo bar="quux" />
could be read as an element with the name foo, and attribute named bar with the value "quux". However, the standard defines that unquoted attribute values should not include escaped characters. And this element
<foo bar="quux" />
should be read as an element with the name foo, and attribute named bar with the value quux without the quotes. This is because in SGML the quotes are optional, and everything up to the next space will be used as the value for the attribute.
XML requires quotes.
There is a difference between an attribute value delimiter and a quote or double quote character.
You have to use a literal " or ' to delimit attribute values (except where delimiters are optional). In this case, the squence of bytes means "attribute value delimited" not "(double) quote mark"
The character references can be used to represent a (double) quote mark but is a more complicated and inefficient way compared to using a literal so should only be used when the literal is not available (i.e. when it would be an attribute value delimiter because you are inside an an attribute value where the opening delimiter was that character).
Just out of curiosity. Why would you want to use the encoded variants? In most of the text editors it will break the formatting. For me that would be very annoying.
You should stick with the double quotes - othewise the attribute might not be correctly read.
<script src=myscript.js></script>
is valid in HTML5 and supported by every significant browser.

Categories