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]+/
Related
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`)
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^
I need some help.
I need to know if it is possible to use the % symbol in javascript.
I ask this question because I have an html table with the following ID= MRRMFBSY_%_CEC.
When I try to keep the TD of the second TR of this table the results is undefined, so it seems that it doesnt find the Table with this ID and also when it is defined well.
See my code below:
function getColumnsVal(id) {
var header = $("table#" + id + " thead tr:eq(1)");
var header_fields = $("td", header);
// If ID = MRRMFBSY_%_CEC when I try to do an alert of one of my TD,
// example the firstone it returns undefined
alert(header_fields[0]);
}
The question if you think that the problem is the % symbol or not, because when I have the other ID it works perfectly.
Thanks in advance
% is a reserved character, since its an operator (see).
It's not recommended, but you can use it as ID in an HTML element.
See this example:
const element = document.getElementById('MRRMFBSY_%_CEC');
console.log(element); // returns the div element
<div id="MRRMFBSY_%_CEC">
My div with a specific ID
</div>
ISSUE:
There is a problem when using certain special symbols %, ^, +, #, and so on, inside a jquery selector. They should be escaped with a backslash(\) when used because they are also used in forming the queries for the selector.
For instance '#divid' is a valid string in JavaScript but would be confusing to use in jQuery if the string was an actual id of an element. To get this element you have to use
$('#\#divid').
So, in your case to get your target element, $('#MRRMFBSY_\%_CEC') will get the element easily. However, you can either insert the escape character(\) manually or programmatically as done in this post with regular expression. Therefore, using the square brackets or the native getElementById in this answer, is just another way out of this problem.
You can definitely use % symbol in an id attribute (or in any string) as you would use the dash symbol -. However, you cannot use either of both for JavaScript variable names as they are reserved symbols.
SOLUTION:
Though this question has its own intricacies, #misorude has pointed out a solution here. So there lies your answer. use the square brackets [] or document.getElementById like this.
function getColumnsVal(id) {
// var element = $('[id="' + id + '"]'); // this line is equivalent to the next line.
var element = $(document.getElementById(id));
var header = element.find($("thead tr:eq(1)"));
var header_fields = $("td", header);
// If ID = MRRMFBSY_%_CEC when I try to do an alert of one of my TD,
// example the firstone it returns undefined
alert(header_fields[0]);
}
Is there a way to do a wildcard element name match using querySelector or querySelectorAll?
The XML document I'm trying to parse is basically a flat list of properties
I need to find elements that have certain strings in their names.
I see support for wildcards in attribute queries but not for the elements themselves.
Any solution except going back to using the apparently deprecated XPath (IE9 dropped it) is acceptable.
[id^='someId'] will match all ids starting with someId.
[id$='someId'] will match all ids ending with someId.
[id*='someId'] will match all ids containing someId.
If you're looking for the name attribute just substitute id with name.
If you're talking about the tag name of the element I don't believe there is a way using querySelector
I was messing/musing on one-liners involving querySelector() & ended up here, & have a possible answer to the OP question using tag names & querySelector(), with credits to #JaredMcAteer for answering MY question, aka have RegEx-like matches with querySelector() in vanilla Javascript
Hoping the following will be useful & fit the OP's needs or everyone else's:
// basically, of before:
var youtubeDiv = document.querySelector('iframe[src="http://www.youtube.com/embed/Jk5lTqQzoKA"]')
// after
var youtubeDiv = document.querySelector('iframe[src^="http://www.youtube.com"]');
// or even, for my needs
var youtubeDiv = document.querySelector('iframe[src*="youtube"]');
Then, we can, for example, get the src stuff, etc ...
console.log(youtubeDiv.src);
//> "http://www.youtube.com/embed/Jk5lTqQzoKA"
console.debug(youtubeDiv);
//> (...)
Set the tagName as an explicit attribute:
for(var i=0,els=document.querySelectorAll('*'); i<els.length;
els[i].setAttribute('tagName',els[i++].tagName) );
I needed this myself, for an XML Document, with Nested Tags ending in _Sequence. See JaredMcAteer answer for more details.
document.querySelectorAll('[tagName$="_Sequence"]')
I didn't say it would be pretty :)
PS: I would recommend to use tag_name over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes.
I just wrote this short script; seems to work.
/**
* Find all the elements with a tagName that matches.
* #param {RegExp} regEx regular expression to match against tagName
* #returns {Array} elements in the DOM that match
*/
function getAllTagMatches(regEx) {
return Array.prototype.slice.call(document.querySelectorAll('*')).filter(function (el) {
return el.tagName.match(regEx);
});
}
getAllTagMatches(/^di/i); // Returns an array of all elements that begin with "di", eg "div"
i'm looking for regex + not + multiClass selector, and this is what I got.
Hope this help someone looking for same thing!
// contain abc class
"div[class*='abc']"
// contain exact abc class
"div[class~='abc']"
// contain exact abc & def(case-insensitively)
"div[class~='abc'][class*='DeF'i]"
// contain exact abc but not def(case-insensitively)
"div[class~='abc']:not([class*='DeF'i])"
css selector doc: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
simple test: https://codepen.io/BIgiCrab/pen/BadjbZe
I liked many of the answers above, but I prefer my queries run only on classes/IDs so they don't have to iterate over every element. This is a combination of code from both #bigiCrab and #JaredMcAteer
// class exactly matches abc
const exactAbc = document.querySelectorAll("[class='abc']")
// class begins with abc
const startsAbc = document.querySelectorAll("[class^='abc']")
// class contains abc
const containsAbc = document.querySelectorAll("[class*='abc']")
// class contains white-space separated word exactly matching abc
const wordAbc = document.querySelectorAll("[class~='abc']")
// class ends with abc
const endsAbc = document.querySelectorAll("[class$='abc']")
Substitute "class" with "id" or "href" to get other matches. Read the article linked below for further examples.
Reference:
CSS attribute selectors on MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
There is a way by saying what is is not. Just make the not something it never will be. A good css selector reference:
https://www.w3schools.com/cssref/css_selectors.asp which shows the :not selector as follows:
:not(selector) :not(p) Selects every element that is not a <p> element
Here is an example: a div followed by something (anything but a z tag)
div > :not(z){
border:1px solid pink;
}
I'm trying to style some breadcrumbs programmatically, because I don't know how many breadcrumbs there will be (due to child categories being set up by the client, etc). I've tried a few ways to count through the a tags and do this, without much success. Basically I just want each a tag to have one more 1rem of left padding than the previous one. Here is my code:
for(var i = 0; i < jQuery('.woocommerce-breadcrumb a').length; i++){
jQuery('.woocommerce-breadcrumb a:nth-child(' + i + ')').css('padding', i + 'rem');
}
Please excuse my bad coding as I'm just a novice with JavaScript/jQuery. And thank you in advance for any help.
If you want to use jQuery inside of pure CSS, you don't have to use the nth-child selector to get each a tag, you could just loop through each a tag by using the jQuery .each() function.
Something like this should work:
$('.woocommerce-breadcrumb a').each(function(i, ele) {
$(ele).css('padding-left', i + 'rem');
});
This will loop through every tag that matches .woocommerce-breadcrumb a, and then apply the relevant css. the .each() function let's you declare an index i in the function, so that lets us use incrementing padding-left for each element.
See this following code pen - http://codepen.io/anon/pen/vLyOMj - for an example as well.
jQuery.each automatically passed an index so there is no reason to do the for loop.
$('.woocommerce-breadcrumb a').each(function(i) {
$(this).css('padding', i + 'rem');
});
https://jsfiddle.net/SeanWessell/79Lnpze8/
I'd suggest, based on your stated requirements:
// selects the <a> elements contained within an element with a
// class-name of 'woocommerce-breadcrumb',
// uses the css() method to update the 'padding-left' property
// with an anonymous function, in which the first argument
// here 'i' (the index of the current element in the set returned
// by the selector):
jQuery('.woocommerce-breadcrumb a').css('padding-left', function (i) {
// returns a concatenated string, formed by the number of 1
// added to the current index and finally with the units
// added:
return 1 + i + 'rem';
});
References:
css().
Is there a way to do a wildcard element name match using querySelector or querySelectorAll?
The XML document I'm trying to parse is basically a flat list of properties
I need to find elements that have certain strings in their names.
I see support for wildcards in attribute queries but not for the elements themselves.
Any solution except going back to using the apparently deprecated XPath (IE9 dropped it) is acceptable.
[id^='someId'] will match all ids starting with someId.
[id$='someId'] will match all ids ending with someId.
[id*='someId'] will match all ids containing someId.
If you're looking for the name attribute just substitute id with name.
If you're talking about the tag name of the element I don't believe there is a way using querySelector
I was messing/musing on one-liners involving querySelector() & ended up here, & have a possible answer to the OP question using tag names & querySelector(), with credits to #JaredMcAteer for answering MY question, aka have RegEx-like matches with querySelector() in vanilla Javascript
Hoping the following will be useful & fit the OP's needs or everyone else's:
// basically, of before:
var youtubeDiv = document.querySelector('iframe[src="http://www.youtube.com/embed/Jk5lTqQzoKA"]')
// after
var youtubeDiv = document.querySelector('iframe[src^="http://www.youtube.com"]');
// or even, for my needs
var youtubeDiv = document.querySelector('iframe[src*="youtube"]');
Then, we can, for example, get the src stuff, etc ...
console.log(youtubeDiv.src);
//> "http://www.youtube.com/embed/Jk5lTqQzoKA"
console.debug(youtubeDiv);
//> (...)
Set the tagName as an explicit attribute:
for(var i=0,els=document.querySelectorAll('*'); i<els.length;
els[i].setAttribute('tagName',els[i++].tagName) );
I needed this myself, for an XML Document, with Nested Tags ending in _Sequence. See JaredMcAteer answer for more details.
document.querySelectorAll('[tagName$="_Sequence"]')
I didn't say it would be pretty :)
PS: I would recommend to use tag_name over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes.
I just wrote this short script; seems to work.
/**
* Find all the elements with a tagName that matches.
* #param {RegExp} regEx regular expression to match against tagName
* #returns {Array} elements in the DOM that match
*/
function getAllTagMatches(regEx) {
return Array.prototype.slice.call(document.querySelectorAll('*')).filter(function (el) {
return el.tagName.match(regEx);
});
}
getAllTagMatches(/^di/i); // Returns an array of all elements that begin with "di", eg "div"
i'm looking for regex + not + multiClass selector, and this is what I got.
Hope this help someone looking for same thing!
// contain abc class
"div[class*='abc']"
// contain exact abc class
"div[class~='abc']"
// contain exact abc & def(case-insensitively)
"div[class~='abc'][class*='DeF'i]"
// contain exact abc but not def(case-insensitively)
"div[class~='abc']:not([class*='DeF'i])"
css selector doc: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
simple test: https://codepen.io/BIgiCrab/pen/BadjbZe
I liked many of the answers above, but I prefer my queries run only on classes/IDs so they don't have to iterate over every element. This is a combination of code from both #bigiCrab and #JaredMcAteer
// class exactly matches abc
const exactAbc = document.querySelectorAll("[class='abc']")
// class begins with abc
const startsAbc = document.querySelectorAll("[class^='abc']")
// class contains abc
const containsAbc = document.querySelectorAll("[class*='abc']")
// class contains white-space separated word exactly matching abc
const wordAbc = document.querySelectorAll("[class~='abc']")
// class ends with abc
const endsAbc = document.querySelectorAll("[class$='abc']")
Substitute "class" with "id" or "href" to get other matches. Read the article linked below for further examples.
Reference:
CSS attribute selectors on MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
There is a way by saying what is is not. Just make the not something it never will be. A good css selector reference:
https://www.w3schools.com/cssref/css_selectors.asp which shows the :not selector as follows:
:not(selector) :not(p) Selects every element that is not a <p> element
Here is an example: a div followed by something (anything but a z tag)
div > :not(z){
border:1px solid pink;
}