Append array value to ID attribute of selected elements - javascript

Simply, i'm trying to use jQuery to append a numeric value (currently stored in an array) to the end of the "id" attribute of a number of specified elements.
$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink').attr("id", // Append modCount[0].toString() to each existing ID);
The struggle I am having is in working out how to append the numeric value as opposed to simply set the ID equal to the numeric value. I don't want to lose the existing ID.
In the example, the preferred resulting ID's should be:
#headerAfirstLink1, #headerAsecondLink1, #headerAthirdLink1, #headerAfourthLink1
(If modCount[0] == 1).
I'm sure it is crucifyingly simple but would appreciate some guidance.
Thanks

You can use .attr(attributeName, function) syntax to update the attribute value for each of the respective element.
$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink')
.attr("id", function(index, oldId) {
// oldId is the attribute value
return oldId + modCount[0];
});
Just in case, to update the attribute of all the elements whose ID starts with header, you can use attribute starts with selector.
$('[id^="header"]').attr('id', function(index, oldId) {
return oldId + modCount[0];
});

Try to use .attr("attrName" , callBack) signature to achieve what you want.
$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink')
.attr("id", function(_,id){
return id + modCount[0];
});
Don't confuse the first parameter passed with callBack. It is index. I just used an underscore there as it is not required in our case. Simply to hide its visual.
Or the best/maintainable approach would be setting a common class (ex: test) to those four elements and use a class selector there instead of multiple selector.
$('.test').attr('id', function(_, id) {
return id + modCount[0];
});

Related

Find elements by id, class and attr combined in jquery

I have the following code:
$("#modal-bool-element").change(function(e) {boolSettings($(e.target))});
function boolSettings(e) {
elem = e;
var boolSettingsParent = elem.closest("#bool-settings");
if (elem.is(":checked") == true) {
elem.val(true);
boolSettingsParent.find("#modal-bool-show").prop("disabled", false);
} else {
elem.val(false);
boolSettingsParent.find(".bool-reset, .bool-offset").hide();
boolSettingsParent.find("#modal-bool-show").val("never");
boolSettingsParent.find("#modal-bool-show").prop("disabled", true);
boolSettingsParent.find("#modal-bool-offsetValue, #modal-bool-reset, #modal-bool-offsetUnit").val("");
}
}
What I would like to do is to pass the value of an atrribute to find method along with the classname or id. That attr is elem.attr("model-id").
I have tried like this:
boolSettingsParent.find(`#modal-bool-show [model-id='{elem.attr(model-id)}']`)
But I am not getting any value. How can I achieve the desired result?
Remove the space:
boolSettingsParent.find(`#modal-bool-show[model-id='{elem.attr(model-id)}']`)
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^
The space means you're looking for a descendant element of #modal-bool-show with that attribute. Without the space, it means you only want #modal-bool-show if it also has that attribute value.
You mentioned a class but haven't shown picking one. To do that, you'd tack on a class selector:
boolSettingsParent.find(`#modal-bool-show[model-id='{elem.attr(model-id)}'].some-class`)
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^
BUT, just the id should be sufficient unless you want to skip the element if it doesn't have that attribute and/or class, because you can't have more than one element in the DOM with the same id — doing so is invalid. So adding more things to the selector is fine if you want the selector not to match anything if the element with that id doesn't have the attribute and/or class, but if you're doing it so the selector matches the "right" element with that id, that's a problem because it means you have more than one element with the same id.
I assumed in the above that you were using some templating system that handled the {...} for you, but if you meant to use a substitution in JavaScript's template literal, they use the format ${...}, not {...}. So:
boolSettingsParent.find(`#modal-bool-show[model-id='${elem.attr(model-id)}'].some-class`)
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^

JQuery Selector - Select with * [duplicate]

Say I'm looking for all elements with an attribute 'data-language', whose value begins with 'java' (would match both 'java' and 'javascript'). I know how to do this:
$('[data-language^="java"]')
But my question is: how do I get all elements that have an attribute (not the value of the attribute, but the actual attribute name itself) beginning with something? For example:
all elements that have an attribute name beginning with "data-s", or
all elements that have data attributes at all (attributes beginning with "data-").
There is no shortcut, you may use the attributes collection :
$(someselector).filter(function(){
var attrs = this.attributes;
for (var i=0; i<attrs.length; i++) {
if (attrs[i].name.indexOf("someStartOfName")==0) return true;
}
return false;
});
jQuery has a nice function for this.
http://api.jquery.com/data/
$("div").data() // returns all data attributes to this div

jQuery - select all elements with attribute name (not value) beginning with...?

Say I'm looking for all elements with an attribute 'data-language', whose value begins with 'java' (would match both 'java' and 'javascript'). I know how to do this:
$('[data-language^="java"]')
But my question is: how do I get all elements that have an attribute (not the value of the attribute, but the actual attribute name itself) beginning with something? For example:
all elements that have an attribute name beginning with "data-s", or
all elements that have data attributes at all (attributes beginning with "data-").
There is no shortcut, you may use the attributes collection :
$(someselector).filter(function(){
var attrs = this.attributes;
for (var i=0; i<attrs.length; i++) {
if (attrs[i].name.indexOf("someStartOfName")==0) return true;
}
return false;
});
jQuery has a nice function for this.
http://api.jquery.com/data/
$("div").data() // returns all data attributes to this div

javascript regular expression

I want to rename the id attribute of an element using jQuery. I need to match the following:
row_1
row_2
row_xx etc
this is what i have so far:
$('.form .newsCategories .row .itemWrap .itemTop .inputBtn').each(function(index){
$(this).attr("id", $(this).attr("id").replace($(this).attr("id").match(/\[row_[0-9]+\]/), "roww_"+index));
});
but this fails. my reg ex is faulty i think. please help
thanks
If I'm understanding the resulting IDs you want, you can just do this:
this.id = "row" + index;
E.g., if you want to find all of them and renumber them in document order:
$("*[id^=row]").each(function(index) {
this.id = "row" + index;
});
That uses an attribute starts-with selector (^=) to find only elements whose id starts with "row", and then renumbers them in document order.
Off-topic: Note that there's no reason at all to use $(this).attr("id"); the DOM element itself has an id property which reflects the id attribute directly.
You have an extra set of square ([ ]) brackets. Change it to:
/row_[0-9]+/
or equivalent:
/row_\d+/
Using the []s creates a character class which you do not need to do. Try this regex...
/row_[0-9]+/

jquery dynamic id

i use such code to access item
function f(id){
$("#"+id).val(); // with analogy $("#id item")
}
is it correct? is any other methods?
If you want to return the value of an element with specified id, then yes as that is what seems to be logical purpose of your function:
function f(id){
return $("#" + id).val();
}
The functions should assume that an element with specified id exists and then it returns you the value of that element. This should work for input fields as well as textarea. If however, it is any other element, you might want to use html() or text() instead of val() eg:
function f(id){
return $("#" + id).html();
// return $("#" + id).text();
}
You could use PureDom
function f(id){
return document.getElementById(id).value;
}
Take that, jQuery!
Yes this is perfectly valid way to access the element having its id.
From the jQuery API website:
.val() Returns: String, Array
Description: Get the current value of
the first element in the set of
matched elements.
What It's not clear to me when you say
// with analogy $("#id item")
is if you want to have ONLY one child item of the one that is identifiedby #id or if you need the item that is identified by item#id.
Your code is perfect if you are passing a string like "hello" inside your code and you want to get the DOM element with ID of #hello.

Categories

Resources