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);
Related
I need to skip this querySelector('input') because in certain instances the input will come second instead of first. Is there a way to label an element in HTML as 'skip this'?
You're free to utilize the full power of CSS syntax there. In your example if you only want to get input if it's the first parent's element then query like this:
querySelector('input:first-child');
Or if you want to get precise use :nth-child selector, or even better, :nth-of-type:
querySelector('input:nth-of-type(1)');
But the best solution would be to mark your input with a class or id and use it instead:
querySelector('.myInput');
You can of course combine it with negation selector:
querySelector('.myInput:not(':nth-child(2)')');
querySelector returns the first Element that matches the selector provided in the method. And why wouldn't it? That's what it's supposed to do.
A.E. the below returns the first input tag it can find on the document from the top-down.
document.querySelector("input");
It will always return the first input tag it can find. You have two options to "skip" the node. You can either write a function to recursively check if the input should be skipped( kind of superfluous and bad looking ) or you can simply be more specific with your selector.
Either way you need to give the input element you want to skip some sort of recognizable trait. That can be a name property or a dataset property or a class or an id - anything that you can programatically check for.
//functional example
function ignoreSkippable() {
let ele, eles = Array.from(document.querySelectorAll("input"));
eles.some(elem => !elem.matches('.skippable') ? ele = elem : false);
return ele;
}
console.log( ignoreSkippable() );
// <input value="second input"></input>
//specific selector example
let ele = document.querySelector("input:not(.skippable)");
console.log(ele); // <input value="second input"></input>
<input class="skippable" />
<input value="second input" />
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.
JS:
this.par = $(this).find("p");
HTML:
<p></p>
The problem is that I dont want to find p tag, but rather a div with a specific ID like this one below.
<div id="abc"></div>
Use the ID selector:
var myDivObj = $("#abc");
Take a look at the list of jQuery selectors.
Additional Information:
It's difficult to tell by your code what you're trying to do, but based on what you've posted, there is no reason to use $(this). The ID selector alone should meet your needs.
Well, you can just use the id selector:
$(this).find('#abc');
Since ids should be unique on the page, you may as well just use it as the constructor:
$('#abc');
If this isn't exactly the same, you're doing something wrong.
this.par = $(this).find("#abc");
You don't want to do that. Don't add properties to the html elements. This is better:
var par = $(this).find('#idOfElement')
Storing the result in this.par is a very bad idea, since this refers to a DomElement.
What you might be looking for is jQuery .data():
$(this).data('par', $(this).find('#idOfElement'))
Which allows you to associate #idOfElement with this.
use id selector
this.par = $(this).find("#abc");
but id is uniqe you can remove $(this).find and use this code
this.par = $("#abc");
How can I get attributes values from an container using jquery ?
For example:
I have container div as:
<div id = "zone-2fPromotion-2f" class = "promotion">
here how can I get attribute id value using jquery and than how can I trim the value to get component information ?
update : how can i get attribute values ?
UPDATE: If I have multiple components on page with same div information than how would I know what attribute value is for which component ?
Thanks.
First, that seems to be a ridiculously long ID -- I'm sure it could be made much shorter while still retaining its uniqueness.
Anyway, on to the answer: First you need a way of accessing your "container" div. Typically, one might use a class or ID to get an element. For example, you could "select" this div with the following call to jQuery:
var container = jQuery('#zone-3a...'); // Fill in ... with really long ID
But, since you're asking how to retrieve the ID, I'm presuming that selecting it via the ID is not an option. You could also select it using the class, although it's not guarenteed to be the only element on the page with that class:
var container = jQuery('.promotion');
There are other ways to narrow down the search, such as:
jQuery('div.promotion');
jQuery('div.promotion:first');
Once you have a reference to your "container", you can retrieve the ID like so:
container.attr('id'); // => zone-3a...
// or:
container[0].id; // => zone-3a...
So assuming your div looks like this.
<div id="foo"/>
You could get the ID attribute by using the attr method.
$("div").attr("id);
That assumes that you only have one div on the page. Not really sure what component information you are looking to get?
You read node attributes with the attr() method.
var id = $( '.promotion' ).attr( 'id' );
In terms of parsing that ID for any other arbitrary information, I can't say since it looks like you're using some sort of proprietary format of which I have no knowledge.
loop thru and get all divs with the class promotion and get the id of each...
$('div.promotion').each(function(){
var attr = $(this).attr('id'); // or whatever attribute
});
or single
var myDivClass = $('zone-3a-2f-2f-2fPortal-2fPages-2fHome-2fZones-2fLeft-2f-7ccomponent-3a-2f-2f-2fSpm-2fComponents-2fPromotion-2f').attr('class');
or another single
var myDivID = $('.promotion').attr('id');
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