jQuery Select # id with word as prefix and counter as suffix - javascript

Is there a way to select all id's with jQuery with a prefix "my" and a suffix "0-9".
Something like these $("#my$1-4") or is it just possible with a loop ?
<div id="my1"/>
<div id="my2"/>
<div id="my3"/>
<div id="my4"/>
<div id="my5"/>

First thoughts, which seems to work well:
$('div[id^="my"]').filter(
function(){
return this.id.match(/\d+$/);
});
JS Fiddle demo.
The above selects all div elements whose id starts with the value my, and then filters the returned elements to those whose id also ends with numeric characters.
References:
attribute-starts-with selector.
filter().
Regular Expressions, at Mozilla Developer Network.

The prefix part is easily achievable with an attribute starts-with selector:
$("div[id^=my]");
But there is no selector that will allow you to specify a range of characters, so a loop will have to be involved. I would suggest filter:
$("div").filter(function () {
return /^my\d$/.test(this.id);
});

Assuming you don't have millions of elements that start with "my", you could do:
$('[id^=my]').filter(function() { return this.id.matches(/\d/) && this.id.length == 3 })
This grabs all elements that have an id starting with "my", contain a number, and are only 3 characters long (so "my54" will not match but "my6" will)

Related

jQuery selector : 'starts-with && ends-with' doesnt work on element with multiple classes

The issue is simply as following, when I try to select a class that starts with a keyword , and ends with another keyword, this works fine, if and only if the element has a single class, if element has multiple classes, the selector will return an empty collection.
Here is code to explain the issue
// try removing custom-class from first element --> returns 2
alert($("div[class^='start'][class*='end']").length) // will return 1 by default , only 1 element has single class.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-class start-mid-end" data-custom="1st Div">
</div>
<div class="start-mid-end" data-custom="2nd Div">
</div>
That's because for the element with class="custom-class start-mid-end", the value of its class attribute begins with custom, not start. Remember, the attribute selectors operate on the attribute value as a single string; they don't care that the class attribute is "special" in HTML.
Regarding a solution to your problem: there aren't any without caveats. As the most practical workaround, I would suggest using multiple classes instead of just one. For example, instead of just prefix-X-suffix also add the classes prefix- -suffix and then you can select your elements simply with
$("div[.prefix-.-suffix]")
Another option would be to use filter to customize the class selection logic, e.g.
$("div").filter(function() { return /\bstart\S*end\b/.test(this.className); })
The regex \bstart\S*end\b matches any sequence of non-whitespace characters with the prefix start and the suffix end, which is what you are after.
The selectors you use refer to the whole attribute string, so class="start what ever end" will be a match.

Jquery [attribute] Selectors

So I've seen several posts explaining how to use a variable in a value for attribute selection. i.e. (where the JS event refers to the div (making it $(this):
HTML
<div id="item1"></div>
<div id="item1" style="display: none;"></div>
JS
var find = $(this).attr("id")
$('div[id="'+find+'"]').show();
But I would like to know how to use a variable in a jquery selector to find something with a similar string to the value of the variable. i.e. finding an element from the example above but looking for "#item1div", where the event target is still "#item1"
HTML
<div id="item1"></div>
<div id="item1div" style="display: none;"></div>
JS
var find = $(this).attr("id")
$('div[id="'+find+"div"'"]').show(); // incorrect syntax
So my question is: How do I correct the above syntax to include an additional string in the attribute check?
I can't find any reference to the correct syntax for how to add compile a string of the value of a variable and an explicit string then check that as the value for x attribute.
I know I can use [id*="'+find+'"] here because the alternate id contains the same characters as the basic one, but I want to know how to target a specific other id based on the first one. For example if I had #item1, #item1div, and #item1img, how can I use an event on "#item1" to find attribute values equal to "item1div" and/or "item1img"
EDIT: I also just realized I can just use [id|="'+find+'"] if I name the divs accordingly with hyphens, but again doesn't solve ids with different endings (or different strings that come after the hyphen)
$('div[id="'+find+"div"'"]') isn't valid Javascript syntax:
$( // jQuery function
'div[id="' // String
+ find // Add variable
+ "div" // Add String
'"]' // Unexpected string! - Error
One example of valid syntax would be:
$('div[id="'+find+'div"]')
However, since it's an id, you can use the id selector instead:
$('div#'+find+'div')
the question is very unclear, but I assume your question boils down to :
Q:how do you search all the elements where it starts with string x ?
A:To get all the elements starting with "item1" you should use:
$("[id^=item1]")
You should use ID selector like below to find an element by ID,
$('#' + find).show();
To find item1div or the dynamic first part - $('#' + find + 'div')
Note: the incorrect syntax you had mentioned is because of a missing + - It should be
// V-- you missed this
$('div[id="'+find+"div"+'"]').show();
To add the explicit string to the attr value you can write as follows
$('[attr="'+attrVal+'extraString"]')
For evample in case of id of div itemdiv
var item1ID = $('#item1').attr('id'); // item1
$('[id="'+item1ID+'div"]') // valid selector to select #item1div

JQuery: Find all ids starting with any one of the specified Strings

I understand that I can use below selector to select a div starting with one string.
$('[id^="content_"]')
Find All Ids starting with a String
I have Divs that starts with Strings "content_" or "list_".
How do I select all divs on my document that starts with one of above 2 strings?
Something like below that should work,
$('[id^="content_"] OR [id^="content_"]')
You can use comma separated list of jquery selectors
$('[id^="content_"],[id^="list_"]')
Use comma to have multiple selectors. It will consider both
$('[id^=content_],[id^=list_]').each(function(){
alert($(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="anchor">Shoaib</div>
<div id="content_anchor">Sajeed</div>
<div id="list_anchor">Chikate</div>

jQuery selector that finds links whose text doesn't begin with something

I need to add an additional limiter to this find() method so that the <a> elements whose text begin with a string of Re: are left out.
$(document).find(".middletext:not(.quoteheader) > a[href^='http://fakeURL.com/']")
The problem is that I don't know of an attribute to represent the text within an <a> tag, and I don't know of a selector that only selects strings that don't begin with something. If a text attribute existed and if a selector that selects strings that don't begin with something looked like this: ^!=, then my code would be:
$(document).find(".middletext:not(.quoteheader) > a[href^='http://fakeURL.com/'][text^!='Re: ']")
How can I make this work?
I suspect there is a way to use filter() after using find() and make it work, but I don't know how.
I'd suggest, as you say, using filter():
$(document).find(".middletext:not(.quoteheader) > a[href^='http://fakeURL.com/']")
.filter(function(){
return $(this).text().indexOf('Re:') !== 0;
}).css('color','red'); // or whatever
References:
JavaScript:
String.prototype.indexOf().
jQuery:
filter().
find().
text().

strip non-numeric values is not working

I want all non-numeric characters to be removed from a div
for example:
<div class="publication_date> c2011. </div>
should appear
<div class="publication_date> 2011 </div>
I tried
$(".publication_date").html($(".publication_date").html().replace(/[^0-9]+/g, ''));
and it is giving all dates as 2000
You need to use .each():
$('.publication_date').each(function() {
$(this).html($(this).html().replace(/\D+/g, ''));
});
The .html() function, when passed no arguments, returns the value for the first element matched by the initial selector. If your first element had been "c2009.", then all of your other elements would have been "2009" instead of "2000".
By using .each(), you handle each "publication_date" element individually.
Also I modified the regex a little; \D means "not a digit".

Categories

Resources