Is is possible to assign a data value to the element below - and use the numbers in the string as the value with jQuery/Vanilla JS?
I want this:
<div class="priceinfo col5">2560kr</div>
To look like this:
<div class="priceinfo col5" data-price="2560">2560kr</div>
The value is dynamic - the class of the element is the same.
This can be done with the jQuery attr() method:
var someValue = 2560;
$('.priceinfo.col5').attr('data-price', someValue);
You can set any attribute, including custom attributes such as HTML5 data- attributes, using attr().
You can also pass a function instead of a fixed value to .attr():
$('.priceinfo.col5').attr('data-price', function() {
var text = $(this).text();
return parseInt(text, 10); //drops the non-numeric characters at the end of the text
});
This is extremely useful when there are multiple elements in the jQuery set -- multiple elements with the classes priceinfo and col5.
If the value might sometimes have initial non-numeric characters, then you could use a regular expression to parse the text:
$('.priceinfo.col5').attr('data-price', function() {
var text = $(this).text();
var matches = /\d+/.exec(text);
if (!matches) {return '';}
return parseInt(matches[0], 10);
});
You can do that with plain javascript as well:
function setAttribute(selector, attribute, value) {
var elements = document.querySelectorAll(selector);
for (var index = 0; index < elements.length; index++) {
elements[index].setAttribute(attribute, (typeof value === "function" ? value(elements[index]) : value));
}
}
Related
The objective is to create multiple sliders on the page by linking the slider to something. The slider must be activated by clicking or hovering the slider anchor. sliderList would be a array for making this process easier so i wouldn't have to link each other manually on the configs js file.
I need to get the attribute value from a element that is inside an array. In this case, holder is the array from where I want to extract the attribute value from the current array element. I tried doing this:
var holder = $('[slider-select]');
for (var i = 0; i < holder.length; i++) {
var sliderList = $('[slider-target='
+holder[i].attr('slider-select')
+']');
}
It looks like +holder[i].attr('slider-select') isn't working. I'm learning JavaScript/Jquery and it's crazy how things goes wrong even when it makes all sense, lol. Let me know if I wasn't clear enough.
The function attr is a built-in function from jQuery, it's a shorthand of function getAttribute and setAttribute.
In your case you want to do this:
var holder = $('[slider-select]');
for (var i = 0; i < holder.length; i++) {
var test = holder[i];
var sliderList = $('[slider-target=' + holder[i].getAttribute('slider-select') + ']');
} ^
A good approach is to use the jQuery built-in functions, so you can use this:
$('[slider-select]').each(function() {
var sliderList = $('[slider-target=' + $(this).attr('slider-select') + ']');
}); ^
Resources
.attr()
getAttribute
setAttribute
.each()
holder[i] contains a plain DOM element, but you're trying to use the jQuery attr method on it. You need to convert it into a jQuery object $(holder[i]) (or else use the native getAttribute on the DOM element):
var holder = $('[slider-select]');
for (var i = 0; i < holder.length; i++) {
// Splitting this up a bit just to make it more readable:
var val = $(holder[i]).attr('slider-select'); // instead of holder[i].attr(...)
var sliderList = $('[slider-target="' + val + '"]');
// confirm we got the element:
console.log(sliderList.text());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div slider-select="A">A</div>
<div slider-select="B">B</div>
<div slider-select="C">C</div>
<div slider-target="A">a</div>
<div slider-target="B">b</div>
<div slider-target="C">c</div>
The attr method is not a function on the JS element object. You'll want to wrap it in jquery to retrieve attribute values instead. For instance
$(holder[i]).attr("slider-select")
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");
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.
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_');
I have an html div element, which contains lot of HTML-5 data- attributes to store extra
data with element. I know that we can use removeAttr of jquery to remove specific attribute,
but i want to know that is there any way to remove data- all atonce?
No, you have to loop through them and remove them individually. E.g.:
var $div = $("selector for the div"),
attrs = $div[0].attributes,
name,
index;
for (index = attrs.length - 1; index >= 0; --index) {
name = attrs[index].nodeName;
if (name.substring(0, 5) === "data-") {
$div.removeAttr(name);
}
}
Live copy | source
...or something along those lines.
Not aware of any wholesale way of doing this. You'd have to loop over the element's attributes with something like
var el = document.querySelector('p');
for (var i=0; i<el.attributes.length; i++)
if (/^data-/i.test(el.attributes[i].name))
el.removeAttribute(el.attributes[i].name);