Select element with percent sign (%) in its id with jQuery - javascript

I have an element like this:
<a id="my%20id" href="#">hello</a>
I've been trying desperately to select it with jQuery, but cannot. I've tried:
$('a#my id') // obviously won't work
$('a#my\ id') // no such luck
$('a#my%20id') // unrecognized expression
$('a#my\%20id') // still unrecognized
$('a#' + encodeURIComponent('my id')) // same thing as 'a#my%20id'
Is it possible to select this at all with jQuery?

You can use attribute selector, giving id in quotes will get the exact id.
Live Demo
$('[id="my%20id"]')

Use the trustworthy document.getElementById:
$(document.getElementById("my%20id")).text();
Performance should be better than using an attribute selector, as you rely on a native method call to find the id. It's a bit more verbose than the other solutions, if that's an issue.

Actually you need a lot of escaping here:
$("#my\\%20id").text("HI");
\% is not a valid escape, you want \\% which will escape correctly and get the correct id.
You can check an example on jsFiddle.

Related

Combe Multiple JS Selectors with jQuery Selector

I am selecting a group of table rows by using the following line of JS:
document.getElementById('tab1_content').contentDocument.documentElement.getElementsByClassName("data1_smaller")
These represent entries in a table of contents. I want to return only those above which also contain the word 'CHAPTER', so I was attempting to use the jQuery :contains() selector to accomplish this and attempted to convert the entire thing into a single jQuery selector; so, to begin with, I tried converting the following invalid line:
document.getElementById('tab1_content').contentDocument.documentElement.getElementsByClassName("data1_smaller").$(":contains('CHAPTER')")
to this:
$("#tab1_content > contentDocument > documentElement > .data1_smaller:contains('CHAPTER')")
The selector above doesn't give an error but it fails to find anything. Does anybody know the correct way to do this?
You can achieve what you want with pure vanilla js just like you tried in the beginning. You just need to do some small adjustments to your code. You can use querySelectorAll() to query all elements matching a selector inside your ID. Something like this should work just by looking at your example, but might need some small adjustments.
[...document.getElementById('tab1_content').querySelectorAll(".data1_smaller")].filter((node) => node.textContent.includes('CHAPTER'))
// Edit, saw in the comments that you're accessing content in an iframe
[...document.getElementById('tab1_content').contentWindow.document.querySelectorAll(".data1_smaller")].filter((node) => node.textContent.includes('CHAPTER'))
I found this solution based on Anurag Srivastava's comments:
$("#tab1_content").contents().find(".data1_smaller:contains('CHAPTER')")
The issue was that I was trying to select things that are inside of an iframe and the the .contentDocument.documentElement that I used to access the iframe in JS has to be changed to .contents() in jQuery in order for it to work.
Neither contentDocument or documentElement are valid HTML tags. Try to select by id or class name.

Finding the number of options in multiple selects that have the same IDs

Firstly, I do know that it is against best practice for multiple elements to have the same ID in a single page. However in this case I need for there to be two selects with the same id.
I have seen some success using this method:
$('#undo_redo_to option').length;
$('#undo_redo_to:eq(0) option').length;
*$('#undo_redo_to:eq(1) option').length;*
However, the code enclosed in *'s does not give me the proper length.
Please see the following pen, where I have created my selects and did my debugging.
LINK TO CODE
Thanks!
The problem is that jQuery uses the native JS functions first, so when you do a $('#this_id') you are effectively calling document.getElementById('this_id'). it's not just against best practice, it actually won't work... you could loop through your selects and check the id:
$('select option').each(function(){
if($(this).closest('select').attr('id')=='my_id'){
//do something
}
});
Assuming you've inherited the HTML and cannot change the ids to classes:
Note that eq() is a jQuery selector. If you change it to nth-child(2), you'll be using a CSS selector. That gives you what you need:
$('#undo_redo_to:nth-child(2) option').length;
http://codepen.io/anon/pen/WwERGW?editors=1011
You can do it with native javascript, like this:
document.querySelectorAll("[id=undo_redo_to]")
You can do it with jquery like this:
$("[id=undo_redo_to]")
This is the property selector, as the #-type selector will stop searching when the first element having that id was found.
So you can do this using plain javascript or jquery, but don't do it, because id should be unique and if it is not unique, then the HTML is invalid and it is bad for SEO.

how get and element using jquery

I know how to choose a element using the Attribute Equals Selector [name="value"] but I feeling a little lost when I try to find a check box by his name and value.
this is a example of the checkbox
<input id="check-box-nat-Español" name="kid[native_languages][]" type="checkbox" value="50f97f5304fec25b00000001">
I have a lot of checkbox with the same name, so I need to find the checkbox using the name and the value.
I'm trying this, but it did not work.
$("input[name="kid[native_languages][]"][value=50f97f5304fec25b00000001]").attr("checked",true);​
Any help please!
use single quotes and it should work
$("input[name='kid[native_languages][]'][value=50f97f5304fec25b00000001]").attr("checked",true);
fiddle
You have error while selecting. You should use:
$("input[name='kid[native_languages][]'][value='50f97f5304fec25b00000001']").attr("checked",true)
Link To Fiddle
Use single quotes around your selector so that they wont interfere with the ones inside
$('input[name="kid[native_languages][]"][value=50f97f5304fec25b00000001]')
$("input[name='kid[native_languages][]'][value=50f97f5304fec25b00000001]").prop("checked",true);​

Prototype.js: select elements with id starts with?

There are tags with attributes id like this
<span id="attr35"></span>
<span id="attr44"></span>
<span id="attr23"></span>
Need to set the style to them like this (last two digits might be any)
$("span[id=attr???]").setStyle({'display':'inline'});
Is it possible?
You use valid Selectors API selectors.
$("span[id^=attr]")
If you want more than one match, use $$
$$("span[id^=attr]")
Oops, one more issue. You should use .invoke if you are getting multiple matches. You can't call setStyle directly on the returned set.
$$("span[id^=attr]").invoke("setStyle", ...)
Since version 1.5.1 the $$ function supports the attribute-startswith-selector ^=:
$$('[id^="attr"]').invoke("setStyle",{display:'inline'});
$$('[id^="attr"]').invoke("setStyle",{'display':'inline'});

jquery selector problem

I'm trying to select a div with the id "about me". I think I am having problems because of the spaces.
alert($link.attr("title"));
I get "about me"
alert($('#'+$link.attr("title")).attr("title"));
I get undefined.
I have tried to use php and jquery methods for removing them but it doesn't work.
So how do I get around this?
You need to remove the spaces, IDs with spaces aren't valid, and you'll have all sorts of issues...just like this :)
You can escape it like this:
alert($('#'+$link.attr("title").replace(/ /g, "\\ ")).attr("title"));
But this is not the correct solution to the problem, removing the spaces is the correct approach.
In general, if you want to get an element by a variable ID it's better to do that via the plain DOM getElementById method than to try to shoehorn it into a selector with all the escaping issues that brings with it. eg:
$(document.getElementById($link.attr("title")))
However, for the particular case of the space character, it's invalid, period; as Nick says, you need to get rid of it. Whilst IDs are much more permissive in HTML5 than they were in HTML4 and XHTML1, even in HTML5 spaces are not allowed.

Categories

Resources