Universal String selector for Javascript? - javascript

I have something like
x.getElementById("foo" + rowIndex);
There are a couple of cases that have some other string before the "foo" in the ID, and my question is if there are any replacements (like the "%" in SQL) that I could use to add something else to the "foo" like
x.getElementById("%foo" + rowIndex);

If you use querySelector instead of getElementById, you can pass a selector string that selects an ID which ends with the substring you want, for example:
x.querySelector('[id$="foo' + rowIndex + '"]');
const rowIndex = 3;
console.log(document.querySelector('[id$="foo' + rowIndex + '"]'));
<div id="barfoo3">text</div>
(of course, if you want to select all elements whose ID ends with that, use querySelectorAll instead of querySelector)
That said, note that such dynamic IDs are somewhat of a code smell - you might consider if there are more elegant alternative methods.

Related

How to set a variable to utilize querySelectorAll to reference all elements selected by the selector [data-clue-A=clue]

I am trying to set wordLetters to reference all elements selected by the CSS selector [data-clue-A=clue] where clue is the value of data-clue-a for the object currentLetter.
I have tried:
wordLetters = document.querySelectorAll('span[data-clue-A = 'currentLetter.dataset.clueA']');
but it gives me error.
It looks like the string isn't in the right form for concatenation.
Try this:
wordLetters = document.querySelectorAll('span[data-clue-A=' + currentLetter.dataset.clueA + ']');

How can id access an array of ids from jquery?

here the snippet of code
var input_form =["first_text","middle_text","last_text","suffix_text","title_text","url_text","day_pnum","mon_pselect","year_pnum","day_anum","mon_aselect","year_anum"];
where "first_text","middle_text",... refers to the different ids in my html
i can access it via document.getElementById(input_form[i]), (within for loop)
but i have to use jquery, so whats wrong when i write the above code in jquery as $(input_form[i]) to get the same result
Since jQuery are query selectors (or CSS selectors), for id you need to prefix with #. So use this way:
$("#" + input_form[i])
You missed the # selector, try with this:
$("#" + input_form[i])
Hope it helps!
for (var i = 0; i < input_form.length; i++) {
var $el = $('#' + input_form[i]);
}
$el would give u the element's jquery reference
For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient. When another selector is attached to the id selector as #.you can use like below:
$("#" + input_form[i])
or
$('[id=input_form[i]]')
For more information check here
Depends on your needs, you can also select all of your input's as one jQuery object, is such case you can for e.g. call .val('') to clean all of them.
Example:
var input_form =["first_text","middle_text","last_text","suffix_text","title_text","url_text","day_pnum","mon_pselect","year_pnum","day_anum","mon_aselect","year_anum"];
var inputs_selector = input_form.map(s => "#" + s).join(",");
// reset all values
$(inputs_selector).val('');

jQuery Finding Element By Id With Space And Via Variable

I am able to locate an element of an element through an id and add a class when the ID is hard coded, e.g:
var tableId = el.id;
$('#' + tableId).find("[id='Checkout On']").addClass('highlight');
However, I want to pass 'Checkout On' as a variable, e.g:
var tableId = el.id;
var childEl = col.id;
$('#' + tableId).find("[id=" + childEl + "]").addClass('highlight');
However this doesn't seem to work.
Update:
Completely understand IDs should not have spaces however this is not something I am able to resolve.
You've left out the quotes in the version using the variable:
$('#' + tableId).find("[id='" + childEl + "']").addClass('highlight');
// ------------------------^---------------^
But note that an id with a space in it is invalid. From the spec:
3.2.5.1 The id attribute
The id attribute specifies its element's unique identifier (ID). [DOM]
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.
(my emphasis)
That means that even if this works on one browser, there's no guarantee it'll work in another, or even in the next minor release of the one where it worked. (I bet it will, but there's no reason to tempt things like that...)
You should never use whitespaces for any id or class names. Go with snake_case or camelCase: checkout_on or checkoutOn
If you want to select an element with ID use the #... selector. It's better. Like this:
var tableId = el.id;
var childEl = col.id;
$('#' + tableId).find("#" + childEl ).addClass('highlight');
NOTE: IDs can not have spaces. Check this for more info.

jQuery update doesnt work but javascript does

I've been trying different methods of getting my page to update one input value when I select something from another. When I try it one way using javascript it works fine, another way via jQuery it doesn't and I honestly don't understand why, could someone point out what I'm missing?
This Javascript works fine: -
function youPickedThis(id, num){
var objID = "any[" + num + "].id"
document.getElementById(objID).value = id
}
But this jQuery doesn't: -
function youPickedThis(id, num){
var objID = "any[" + num + "].id"
$("#"+objID).val(id);
}
The objects on the being used/references are all loaded in during the page load via AJAX calls etc, is this something to do with what's causing the issue?
Thanks for any pointers, if anyone has any good links to read explaining this stuff better I'd be very appreciative! :)
Also tried this but still no dice...
$(document).ready(function(){
function updateHiddenInput(id, num){
var objID = "any[" + num + "].id";
$("#"+objID).val(id);
}
});
There's a difference between a jQuery selector and document.getElementById. The second does less, so it knows that whatever you give it will be looked at as an id. For example:
var objID = "any[" + num + "].id"
$("#"+objID).val(id);
What will this look for? Let's presume num is 1, say:
$('#any[1].id').val(id);
This looks for an element with the id #any, an attribute 1, and a class id, because the characters []. all have special meanings in a selector. To demonstrate this, run the following line of code in the browser console:
$('<div id="any" class="id" 1="foo"/>').is('#any[1].id') // returns true
The best way to do this selection is to do the selection with document.getElementById, and then wrap it in the jQuery constructor:
$(document.getElementById(objID)).val(id);
It is possible to escape the special characters with \\, but it becomes increasingly unwieldy and hard to (a) write and (b) read.
You have this:
function youPickedThis(id, num){
var objID = "any[" + num + "].id"
$("#"+objID).val(id);
}
This results in objID having some value like any[3].id, so your jQuery looks like this: $("#any[3].id").val(id); jQuery interprets the .id as a class. Escape it like this:
function youPickedThis(id, num){
var objID = "any\\[" + num + "\\]\\.id"
$("#"+objID).val(id);
}
You should escape square brackect and dot
var objID = "any\\[" + num + "\\]\\.id";
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").
REFERENCE
http://forum.jquery.com/topic/jquery-jquery-wont-recognise-attribute-names-containing-square-brackets#14737000000283511
As others have mentioned, there are differences between jQuery selector and document.getElementById. As jQuery selector has to parse the string and some characters like [,] have special meaning while document.getElementById treats all this as part of an id. You could try escaping those special characters as mentioned by others. Here I give another solution.
You could try id attribute selector. It does something similar to document.getElementById
function youPickedThis(id, num){
var objID = "'any[" + num + "].id'"
$("[id="+objID+"]").val(id);
}
DEMO

What is the most efficient method for adding/removing classes from DOM elements using Javascript?

I'm iterating over a large number of dom elements in Javascript, and I'd like to add/remove classes as appropriate.
What's the most efficient add/remove class operation I can use?
Small class strings: JSPerf.
Bigger class strings: JSPerf.
Bigger class strings, repeated class names: JSPerf.
Remove
The fastest reliable way (small/medium size):
var clss = 'classToRemove';
elem.className = (' '+elem.className+' ').split(' ' + clss + ' ').join(' ');
If you know for sure that the string does not contain multiple occurrences of the same class name, you can better use the string.replace method (any size):
var clss = 'classToRemove';
elem.className = (' '+elem.className+' ').replace(' ' + clss + ' ', ' ');
The other alternatives:
Using a RegExp in combination with replace - Slow in all cases
Using indexOf to find the position, and use string concatenation (substring) to remove the class (repeat this in a loop to remove all possible duplicates).
Slowest for large strings with repetition, not slow neither fast in other cases.
Add (without doubt):
var clss = 'classToAdd';
element.className += ' ' + clss;
The bottleneck is in retrieving the elements, not adding/removing class names.
el.className = "another_class"; //Simple
Depending on the structure of your DOM, you can optimize element retrieval by practicing the following:
Getting a particular wrapper element via getElementById
Getting related sub-elements with getElementsByTagName or childNodes (depending which is more appropriate for the situation)
If referenced recursively, saving references to the accessed elements
Typically, a framework will retrieve elements much more slowly than a vanilla Javacript method, but if you save references by dumping accessed elements in a local array, the difference is near negligible.
Edit: getElementsByClassName is another way to retrieve elements, but it isn't as well supported as the above methods yet.
Again, if we could see your code, we could give a more direct answer.
Where supported, element.classList is around 1000 times faster than Rob_W's best suggestions (no ie8/9 support, although a fallback from Mozilla exists).
http://jsperf.com/best-way-to-remove-class/6
Rob_W's tests were flawed because they were not using the DOM-- just really testing the performance of various string replacements (see tests).
Without jQuery:
function addClass(domElement, class) {
var classes = domElement.getAttribute("className");
if (!classes.indexOf(class))
classes += " " + class;
domElement.setAttribute("className", classes);
}
function removeClass(domElement, class) {
domElement.setAttribute("className", domElement.getAttribute("className").replace(class, ""));
}

Categories