I have an element with many classes, I would like to access a specific class to get the last digit of it (I realize a data-attribute or ID may have been better options but for now I am stuck with class). I already am able to select the element using it's ID so I only need to identify what the last digit of the my-target-* is.
Example
<div class="foo bar apple my-target-1"></div>
I would like to get the class my-target-* and then extract the 1 from it.
Loop over all the elements containing 'my-target', assuming it is the last class, split the classes by space, get the last class, split it by '-' then get the needed value to extract.
Here is a working example:
$(document).ready(function(){
$("[class*= my-target]").each(function(){
var extract= $(this).attr('class').split(' ').pop().split('-').pop();
$("#result").html(extract);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo bar apple my-target-1"></div>
<span id="result"></span>
Here's a jQuery selector that should target your element:
$("[class*=my-target]");
But this may be more general than you need: this uses the CSS substring selector *=, so this would also match elements like the following:
<div class="not-my-target"></div>
You can try a combination of selectors to get something more specific:
$("[class^=my-target], [class*= my-target"]);
This combines the CSS starts with selector, with the contains.
Now to grab the data that you want from the class name you'll need to do some string parsing on the class attribute:
var numberToExtract = -1;
var elem = $("[class*=my-target-]");
if (elem)
{
classes = elem.attr("class").split(/\s+/);
$.each(classes, function(idx, el)
{
if (el.startsWith("my-target-"))
{
numberToExtract = el.split("-").pop();
return false;
}
});
}
Maybe is neater if you use a data element to do this
<div class="foo bar apple my-target-1" data-target="1"></div>
And you get this by doing:
$('.my-target-1').data('target')
It's better than parsing the class
To get any one starting with those classes try this
$('div[id^=foo bar apple my-target]')
If you're stuck using a class instead of a data attribute, you can extract the full string of classes from the object you've found with:
obj.attr('class')
and then match that against a regular expression that uses word boundaries and capturing parentheses to extract the number at the end of 'my-target-*'
You must have ID to catch the particular div or span content.
Be Careful , Perhaps , you have a class and a subclass .
<div id='id' class='myclass mysubclass' >Testing</div>
So if you want to have the class selector, do the following :
var className = '.'+$('#id').attr('class').split(' ').join('.')
and you will have
.myclass.mysubclass
Now if you want to select all elements that have the same class such as div above :
var class=$('.'+$('#id').attr('class').split(' ').join('.'))
that means
var class=$('.myclass.mysubclass')
If you want second class into multiple classes using into a element
var class_name = $('#id').attr('class').split(' ')[1];`
or You can simply use var className = $('#id').attr('class'); this will return full name class and subclass then handle it using JQuery/JavaScript substring method.
Related
I'm wondering how to reference an HTML id or a class in JavaScript in the following context.
<script type="text/javascript">
(function() {
var menu = document.querySelector('ul'),
menulink = document.querySelector('**REFERENCE CLASS**');
menulink.addEventListener('click', function(e) {
menu.classList.toggle('active');
e.preventDeafult();
});
})();
</script>
I'd appreciate any help I can get, thanks.
Let's say you have an element with class attribute equals to "my-class" and you want to select that element with JavaScript. Here as an example i'll select an element based on its class attribute and change his color to green using only JavaScript.
// referencing the element with class attribute containing my-class using querySelector() method that you used it in your code, notice the " . " (dot) before the class-name
var myClassDiv = document.querySelector('.my-class');
// changing the text color to green
myClassDiv.style.color = '#0F0';
<div class="my-class">by default my color is black but JavaScript made me green !</div>
Explanation:
The method querySelector() receives a string representing a fully qualified CSS selector. i.e querySelector('body #main > ul.menu > li.class-name') and as the same selector can match many elements in the same document this method returns only the first element matched by the selector.
To get all the elements matching a selector you could use querySelectorAll() that returns an array of the matched elements.
You wanted to select an element based on it's class-name, JavaScript provides a method that fetches all the elements based on a class-name: getElementsByClassName() that returns an array containing the matched ones even if there is only one element. It rereceives a string representing a class-name, NOT as you write it in CSS i.e getElementsByClassName('class-name') NO dot before the class-name.
To do the same task as we did in the top of that answer
, I'll be using the getElementsByClassName() instead of querySelector().
// referencing the element with class attribute containing my-class
var myClassDiv = document.getElementsByClassName('my-class')[0];
// changing the text color to green
myClassDiv.style.color = '#0F0';
<div class="my-class">by default my color is black but JavaScript made me green !</div>
Hope I pushed you further.
Is there a way to get all the elements that don't start with the id foo in JavaScript?
I tried the following:
var elements = document.querySelectorAll('[id!=foo]');
That doesn't work.
Basically I want the opposite of:
var elements = document.querySelectorAll('[id^=foo]');
Use the :not() selector:
document.querySelectorAll(":not([id^='foo'])");
You can use the :not pseudo selector to match everything except [id^="foo"]:
var elements = document.querySelectorAll(':not([id^=foo])');
Just select all and then filter out the one with the id
document.querySelectorAll("*").filter(...)
I have an element that contains an input text, to get the input text I'm using the jQuery method find.
The input text has a class name like this page-id-x with the x is variable, so I want to select that number after the substring page-id, and this is what I tried :
var id = ui.item.find('input').attr('class').split(/\s+/).filter(function(s){
return s.includes('page-id-');
})[0].split('-')[2];
console.log(id);
I think this code is too complicated, but I couldn't figure out some other way to do it.
If someone knows a better way, I'll be thankful.
Thanks in advance.
I'm going to assume the x part of page-id-x, not the id part, is what varies (since that's what your code assumes).
Another way to do it is with a regular expression, but I'm not sure I'd call it simpler:
var id = ui.item
.find('input')
.attr('class')
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
Example:
var ui = {
item: $("#item")
};
var id = ui.item
.find('input')
.attr("class")
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
console.log(id);
<div id="item">
<input class="foo page-id-23 bar">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The above makes the same assumptions your current code does, which are:
The first input in ui.item is the one you want
It will have the relevant class name
I assume those are okay, as your question is asking for an alternative, suggesting what you have is working.
As you're using jQuery, take a look at this: https://api.jquery.com/category/selectors/attribute-selectors/
For your case, you can use $('[class^="page-id-"'). These types of selectors (listed on the link above) actually work in CSS, too. (At least most should, if not all.)
To get the number after page-id-, my suggestion would be to store that number in some other HTML attribute, like data-pageID="1" or the like.
So you could have:
<div id="page-id-3" data-pageID="3">CONTENT</div>
Then, when you have the DOM element using $('[class^="page-id-"'), you can access that number with .attr('data-pageID').val().
If you can control the HTML markup, instead of using class names, you can use data attributes instead. For example, instead of:
<input class="page-id-1">
You can use:
<input data-page-id="1">
Then jQuery can find this element effortlessly:
$('[data-page-id]').attr('data-page-id')
You can find your element using the *= selector.
let elem = document.querySelector('[class*=page-id-]')
Once you have the element, you can parse the id out:
let [base, id] = elem.className.match(/page-id-(\d+)/)
console.log('page id: %s', id);
<a href="javascript:void(0)" class="PrmryBtnMed"
id = "VERYLONGTEXT"
onclick="$(this).parents('form').submit(); return false;"><span>Dispatch to this address</span></a>
I have been using
var inPage = document.documentElement.innerHTML.indexOf('text to search') > 0,
el = document.querySelector(".PrmryBtnMed");
if (inPage && el) el.click();
But now, the class name has changed: there’s a space and some new text in the class name:
<a href="javascript:void(0)" class="PrmryBtnMed ApricotWheat"
id = "VERYLONGTEXT"
onclick="ApricotWheat(this); return false;"><span>Dispatch to this address</span></a>
How can I change el = document.querySelector(".PrmryBtnMed");
to find the right class?
I tried using el = document.querySelector(".PrmryBtnMed.ApricotWheat"); but that didn’t work.
Next, I tried to add a space (and escape using a backslash): el = document.querySelector(".PrmryBtnMed\ ApricotWheat"); but that didn’t work either.
So, I wondered if I could use %20 for the space.. but no luck.
I’d be very grateful for some help! What am I doing wrong?
Classes can't have spaces, what you have there is an element with two separate classes on it. To select an element with two classes, you use a compound class selector:
document.querySelector(".PrmryBtnMed.ApricotWheat");
That selects the first element in the document that has both the PrmryBtnMed class and the ApricotWheat class. Note that it doesn't matter what order those classes appear in in the class attribute, and it doesn't matter whether there are also other classes present. It would match any of these, for instance:
<div class="PrmryBtnMed ApricotWheat">...</div>
or
<div class="ApricotWheat PrmryBtnMed">...</div>
or
<div class="PrmryBtnMed foo baz ApricotWheat">...</div>
etc.
Also note that the quotes you're using around HTML attributes are sporatically invalid; the quotes around attributes must be normal, boring, single (') or double ("), they can't be fancy quotes.
Live example with quotes fixed and using the selector above:
var el = document.querySelector(".PrmryBtnMed.ApricotWheat");
if (el) {
el.click();
}
function ApricotWheat(element) {
alert(element.innerHTML);
}
<span>Dispatch to this address</span>
There can be no spaces in a class name ... there are two different classes in the element ... use ".PrmryBtnMed.ApricotWheat"
class="PrmryBtnMed ApricotWheat" In this instance you have 2 different classes,
so you need to use the AND condition in your query.
There are many input elements which IDs are
question5,question6, question7
,..., how to select these input elements using Jquery?
I do not mean $('#question5'), I mean to select the group of them.
Also How to get the the last number like 5,6,7,... using Jquery?
You can select all the input elements whose its id starts with 'question', and then you can extract the number, eg.:
$('input[id^=question]').blur(function () {
var number = +this.id.match(/\d+/)[0];
});
Just be careful because if the regular expression doesn't matchs, it will throw a TypeError, a safer version would be something like this:
$('input[id^=question]').blur(function () {
var match = this.id.match(/\d+/);
var number = match ? +match[0] : 0; // default zero
});
Try this:
$("input[id^='question']")
It will match input elements that have an id attribute that begin with question.
Once you have the elements, you can simply do a javascript substring on them to find the number:
$("input[id^='question']").each(function() {
alert(this.id.substr(8));
});
The easiest solution is probably to give the elements a common class that you can select:
<input id="question5" class="questions">
<input id="question6" class="questions">
<input id="question7" class="questions">
You cane then select all of them with $(".questions") and you can get their id:s with the jQuery .attr() function.
add a class to each input field.
<input class='questions'>
$('.questions')
using the select method on the class will do the trick
depending on what you are trying to do, using the jQuery selector for the class you can add a .each to iterate through the array, like so.
$('.questions').each(function (i){
//i = the current question number
alert('this is question '+i);
});
Also, here is further documentation on the .each method in jQuery