Javascript / jQuery : Select class name that contains word - javascript

How can I do this:
I have object that has multiple classes. My goal is to get class name that has string(e.g. 'toaster') in it (or starting with that string) and put it in variable.Note that I know only the beggining of class name and I need to get whole.
e.g. <div class="writer quite-good toaster-maker"></div>
I have this div as my jQuery object, I only need to put class name toaster-maker in variable className;
Again I don't need to select object! I only need to put class name in variable.

A regular expression seems to be more efficient here:
classNames = div.attr("class").match(/[\w-]*toaster[\w-]*/g)
returns all class names that contain "toaster" (or an empty array if there are none).

So, assuming you already have a jQuery object with that div, you could get the value of the class attribute, split the string into the class names, iterate over them and see which one contains toaster:
var className = '';
$.each($element.attr('class').split(/\s+/), function(i, name) {
if (name.indexOf('toaster') > -1) { // or name.indexOf('toaster') === 0
className = name;
return false;
}
});
jQuery doesn't provide an specific function for that.
If you have multiple elements for which you want to extract the class names, you can use .map:
var classNames = $elements.map(function() {
$.each(this.className.split(/\s+/), function(i, name) {
if (name.indexOf('toaster') > -1) { // or name.indexOf('toaster') === 0
return name;
}
});
}).get();
classNames will then be an array of class names.
In browser which support .classList, you could also use $.each(this.classList, ...) instead of $.each(this.className.split(/\s+/), ...).

try this,
var names = $('[class*=toaster]').attr('class').split(' ');
var className;
$.each(names, function(){
if (this.toLowerCase().indexOf("toaster") >= 0)
className = this;
})
console.log(className);
fiddle is here. You can also have className as an array and push the matched class names to it.

Related

jQuery selecting attribute value of multiple elements with name attribute

I have a form that has multiple input, select, textarea elements. With jQuery, How can I get the name attribute values of each element? I have tried the following but its not working:
var names = $('[name]');
names.each(function(){
console.log(names.attr('name'));
})
You need to use this within the each() to refer to the element within the current iteration. Your current code is attempting to get the name of a set of elements which is logically incorrect. Try this:
var names = $('[name]');
names.each(function(){
console.log($(this).attr('name'));
})
You are still using names within your each function. Try this:
var names = $('[name]');
names.each(function(index, name){
console.log($(name).attr('name'));
})
This should loop around all the required elements and output the name and value to the console.
$('input,select,textarea').each(function() {
var thisname = $(this).attr('name');
var thisval = $(this).val();
console.log('name = ' + thisname);
console.log('value = ' + thisval);
});
You can try this way too.
var $name = $("[name]");
$name.get().map(function(elem,index){
console.log($(elem).attr("name"));
});
Add a class to all the elements you wish to get the names of.
Then you get all the elements from that class and iterate them to get their names.
formElements = $('.form-element');
for(key in formElements) {
name = formElements[key].attr('name');
// do what you wish with the element's name
}
P.S. You may need to wrap formElements[key] in $(), have not tested it.
// Selects elements that have the 'name' attribute, with any value.
var htmlElements = $("[name]");
$.each(htmlElements, function(index, htmlElement){
// this function is called for each html element wich has attribute 'name'
var $element = $(htmlElement);
// Get name attribute for input, select, textarea only
if ($element.is("input") ||
$element.is("select") ||
$element.is("textarea")) {
console.log($element.attr("name"));
}
});
Give your input ID then call attr() method
$("#id").attr("name");

jQuery - extract class name that 'starts with' prefix [duplicate]

This question already has answers here:
Get class list for element with jQuery
(16 answers)
Closed 9 years ago.
My items have the following classes:
<div class="class-x some-class-1 other-class"></div>
<div class="some-class-45 class-y"></div>
<div class="some-class-123 something-else"></div>
I'm wondering if there is an easy way to:
Grab only all classes with some-class- prefix.
Remove them from each element.
Have their names (not corresponding DOM elements) in a variable?
I can easily select such elements with jQuery( "div[class^='some-class-'], div[class*=' some-class-']" ) but how its class name could be extracted with the shortest and the most readable code to a variable (can be some global object)?
Like this?
var arrClasses = [];
$("div[class*='some-class-']").removeClass(function () { // Select the element divs which has class that starts with some-class-
var className = this.className.match(/some-class-\d+/); //get a match to match the pattern some-class-somenumber and extract that classname
if (className) {
arrClasses.push(className[0]); //if it is the one then push it to array
return className[0]; //return it for removal
}
});
console.log(arrClasses);
Fiddle
.removeClass() accepts a callback function to do some operation and return the className to be removed, if nothing to be removed return nothing.
You could loop through all the elements, pull the class name using a regular expression, and store them in an array:
var classNames = [];
$('div[class*="some-class-"]').each(function(i, el){
var name = (el.className.match(/(^|\s)(some\-class\-[^\s]*)/) || [,,''])[2];
if(name){
classNames.push(name);
$(el).removeClass(name);
}
});
console.log(classNames);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class-x some-class-1 other-class"></div>
<div class="some-class-45 class-y"></div>
<div class="some-class-123 something-else"></div>
You can iterate over each found node and iterate over the classes to find a match; if found, remove the class and log it:
var found = [];
$('div[class*="some-class-"]').each(function() {
var classes = this.className.split(/\s+/),
$this = $(this);
$.each(classes, function(i, name) {
if (name.indexOf('some-class-') === 0) {
$this.removeClass(name);
found.push(name);
}
});
});
Note that a selector like div[class*="some-class-"] is pretty expensive and since you need to perform extra processing anyway, it would be easier to just iterate over all div tags and process them:
var elements = document.getElementsByTagName('div'),
found = [];
$.each(elements, function(i, element) {
var classes = element.className.split(/\s+/);
$.each(classes, function(i, name) {
if (name.indexOf('some-class-') === 0) {
$(element).removeClass(name);
found.push(name);
}
});
});
Modern browsers expose Element.classList which you can use to manipulate class names and Array.forEach for iteration:
var found = [];
[].forEach.call(document.getElementsByTagName('div'), function(element) {
(function(names, i) {
while (i < names.length) {
var name = names[i];
if (name.indexOf('some-class-') === 0) {
names.remove(name);
found.push(name);
} else {
++i;
}
}
}(element.classList, 0));
});
The easy way
You clould create your own filter :
$.fn.hasClassStartsWith = function(className) {
return this.filter('[class^=\''+className+'\'], [class*=\''+className+'\']');
}
var divs = $('div').hasClassStartsWith("some-class-");
console.log(divs.get());
See fiddle

javascript, selecting one value from object that starts with specific letters

I am selecting all classes from an attribude like so:
var sOption = $(this).attr('class');
in console.log it returns test_1 custom_selectbox
From this i want it to select the class that starts with test_, so with this example it would only return test1. I did the following like so:
var sOption = $.trim($(this).attr('class').replace('custom_selectbox',''));
In this sittuation it returns what i want, but if i add more classes to the attribute where it takes the classes, i would need to also add those class names into replace area:
var sOption = $.trim($(this).attr('class').replace('custom_selectbox','' , 'more_classes', '', 'and_so_on' , ''));
What i want is - instead of using trim and replace , get the test_ classes from the object using regular expressions (bad example):
var sOption = $(this).attr('class'); //get the `test_1 custom_selectbox`
//somehow use the regular expression on this object, so it would select an item from sOption that starts with `test_`
Hopefully i made it understandable what im looking for..
You may split the string into an array, using space as item delimiter, and then filter that array for elements that match your string:
"test_1 custom_selectbox"
.split(' ')
.filter(function(x) { return x.indexOf('test_') == 0; })
You could of course extract that to a plugin:
$.fn.getClasses = function(prefix) {
return $(this).attr('class').split(' ').filter(function(x) { return x.indexOf(prefix) == 0; });
};
Called like so:
$(this).getClasses('test_');

use variable part of ID with js

I have a list of 8 divs: #video1, #video2, ... with each the same javascript actions to run when clicked, but with other id's (for #video1: show #image1, #preview1, ...).
Instead of writing 8 times the same code but with other id's, can I do this more efficient? Is it possible to take the sixth caracter (the number) from each #videoX as a variable when clicked, and use
this in the code?
Inside your event handler, you can extract the number, e.g. with a regular expression [MDN]:
var id = element.id.match(/\d+$/)[0];
and then use it to create the IDs of the other elements:
var image_id = "image" + id,
preview_id = "preview" + id;
Another option would be to assign data- attributes to the elements and use them to store the numerical part of the ID.
Use a class name instead. This way it's independent of the IDs completely.
<div class="videoClick" id="...">...</div>
JS:
$('.videoClick').click(function() {
...
})
yes you can:
$("div[id*='video']").click(function() {
var numid = $(this).attr("id").replace("video", "");
alert(numid);
//...use your numid value
});
Check attribute contains selector.
Try this
var ids = [#video1, #video2, #video3, #video4, #video5, #video6, #video7, #video8];
$(ids.join(",")).click(function(){
var imageId = this.id.replace("video", "image");
var previewId = this.id.replace("video", "preview");
$("#"+imageId).show();
$("#"+previewId).show();
});

jQuery Selecting Elements That Have Class A or B or C

I working on something where I need two functions.
1 - I need to look at a group of children under the same parent and based on a class name, "active", add that element's ID to an array.
['foo-a','foo-b','foo-d']
2 - I then iterate through all the children in another parent and for each element I want to find out if it has any class name that match the ids in the array.
Does this element have class foo-a, foo-b or foo-d?
For the first part, I'd use map and get:
var activeGroups = $('#parent .active').map(function() {
return this.id;
}).get();
This gives you an array of id values (say, ['foo-a', 'foo-d']). You can then make a selector like .foo-a, .foo-b, .foo-c (the multiple selector) using join:
var activeSelector = '.' + activeGroups.join(', .');
This makes a valid jQuery selector string, e.g. '.foo-a, .foo-d'. You can then use this selector to find the elements you want using find:
var activeEls = $('#secondParent').find(activeSelector);
You can then do whatever you need to with activeEls.
var active = $("#foo").find(".active").map(function() {
return this.id;
}).get();
$("#anotherParent *").each(function() {
var that = this;
var classes = $(this).attr("class");
if(classes.indexOf(" ") !== -1) {
classes = classes.split(" ");
} else {
classes = [ classes ];
}
$.each(classes, function(i, val) {
if($.inArray(val, active)) {
// this element has one of 'em, do something with it
$(that).hide();
}
});
});
There's always .is('.foo-a, .foo-b, .foo-d'). Or if you actually just wanted to select them, instead of iterating and deciding for each element, $('.foo-a, .foo-b, .foo-d', startingPoint).

Categories

Resources