I'm attempting to find the value of all elements with the class bm-user-label, and put it into a javascript array. However when I do this I only get the first two characters of the value field. For instance for:
value="30bb3825e8f631cc6075c0f87bb4978c"
I get returned
30
The DOM looks like
<li value="30bb3825e8f631cc6075c0f87bb4978c" class="cboxElement bm-user-label">first</li>
And my javascript is:
var com_labels = $('.bm-user-label').map(function() {
return(this.value);
}).get();
Any ideas?
<li> elements are not defined to have a value. You should get this attribute using this.getAttribute("value") instead.
In an effort to follow the doctype standards, you should use data attributes for non-native attributes:
<li data-value="30bb3825e8f631cc6075c0f87bb4978c" class="cboxElement bm-user-label">first</li>
And query it as such:
var com_labels = $('.bm-user-label').map(function() {
return($(this).data('value'));
}).get();
http://jsfiddle.net/sTdWY/
Related
I need to change the href of link in a box. I can only use native javaScript. Somehow I have problems traversing through the elements in order to match the correct <a> tag.
Since all the a tags inside this container are identical except for their href value, I need to use this value to get a match.
So far I have tried with this:
var box = document.getElementsByClassName('ic-Login-confirmation__content');
var terms = box.querySelectorAll('a');
if (typeof(box) != 'undefined' && box != null) {
for (var i = 0; i < terms.length; i++) {
if (terms[i].href.toLowerCase() == 'http://www.myweb.net/2/') {
terms[i].setAttribute('href', 'http://newlink.com');
}
}
}
However, I keep getting "Uncaught TypeError: box.querySelectorAll is not a function". What do I need to do in order to make this work?
Jsfiddle here.
The beauty of querySelectorAll is you dont need to traverse like that - just use
var terms = document.querySelectorAll('.ic-Login-confirmation__content a');
And then iterate those. Updated fiddle: https://jsfiddle.net/4y6k8g4g/2/
In fact, this whole thing can be much simpler
var terms = document.querySelectorAll('.ic-Login-confirmation__content a[href="http://www.myweb.net/2/"]');
if(terms.length){
terms[0].setAttribute('href', 'http://newlink.com');
}
Live example: https://jsfiddle.net/4y6k8g4g/4/
Try This:
var box = document.getElementsByClassName('ic-Login-confirmation__content')[0];
Since you are using getElementsByClassName ,it will return an array of elements.
The getElementsByClassName method returns returns a collection of all elements in the document with the specified class name, as a NodeList object.
You need to specify it as follows for this instance:
document.getElementsByClassName('ic-Login-confirmation__content')[0]
This will ensure that you are accessing the correct node in your HTML. If you console.log the box variable in your example you will see an array returned.
you can select by href attr with querySelector,
try this:
document.querySelector('a[href="http://www.myweb.net/2/"]')
instead of defining the exact href attribute you can simplify it even more :
document.querySelector('a[href?="myweb.net/2/"]'
matches only elments with href attribute that end with "myweb.net/2/"
I have a long dynamically generated list each with the same class identifier and a data attribute similar to the code below:
<ul>
<li class="list" data-id="123">One</li>
<li class="list" data-id="124">Two</li>
<li class="list" data-id="125">Three</li>
<li class="list" data-id="126">Four</li>
.....etc
</ul>
what I am trying to achieve is to get all the data-id values and format them in as follows:
123|124|125|126....etc
this would be then passed to a page via ajax and the id's checked for existence in a database.
var delimited_data="";
$('.list').each(function(){
delimited_data+=$(this).data('id')+"|";
});
console.log(delimited_data);
The reason I am asking this question is that I am working on a live system that automatically deploys items in the list columns to different users after 10 mins. I just need to be sure that the code is going the right way :)
I also need to check that is there are no .list classes on the page (ie - no way to do the query) whether delimited_data will be totally empty which I am pretty sure it would be.
Is there a better way than using .each() in this case as I find it can be rather slow baring in mind that the above function will be run every 30 seconds.
You can use .map to return an array:
var dataList = $(".list").map(function() {
return $(this).data("id");
}).get();
console.log(dataList.join("|"));
Demo: http://jsfiddle.net/RPpXu/
Use this:
var array = [];
$('li.list').each(function() {
array.push($(this).data('id'));
})
var joined = array.join('|');
Not an answer to your question but this is what i ended up on this page in search for and though it would help someone else :-)
var arrayOfObj = $('input').map(function() {
return {
name : $(this).attr('name'),
data : $(this).data('options'),
value : $(this).val(),
id : $(this).attr('id')
}
}).get();
console.log(arrayOfObj)
This returns an array of objects that mimics the input
Cheers!
as an update for #tymeJV answer for new versions of JavaScript you can use .map((index, elem) => return value) like this:
let result = $(".list").map((index, elem) => elem.dataset.id).get().join('|');
is there a way to get a element that have a attribute with a value. The attribute have multiple values. The values are space separated.
<div data-bind-contains="Header-Logo Footer-Logo"></div>
The problem with $('[data-bind-contains*=Header-Logo]') it will return all. That elements $('[data-bind-contains*=Header-Logo-Something]'), too.
<div data-bind-contains="Header-Logo Footer-Logo"></div>
<div data-bind-contains="Header-Logo-Looper"></div>
The selector $('[data-bind-contains*=Header-Logo]') will return both what is not my intention.
Use ~ (Attribute contains word) match selector
$('[data-bind-contains~=Header-Logo]')
This will give you exact word matched within the attribute value, so this should exclude yourword-something.
Fiddle to demonstrate the difference.
Doc
From your question, you seem have no guarantee that "Header-Logo" is the first string in your list of values.
It's surely not a problem to more specifically test the value against a proper regex in the function called by the selector, is it? This may be a bit longer than needed but shows the idea....
$('[data-bind-contains*=Header-Logo]').click( function() {
var str = $(this).attr('data-bind-contains');
var pat=/\bHeader-Logo\b/;
if (str.match( pat)) {
// do some stuff
}
});
Try this
$('[data-bind-contains*="Header-Logo "]')
This return elements that have data-bind-contains attribute value start with "Header-Logo "
Put a space at the and of attribute value in jQuery so it only returns element that have value "Header-Logo<space>+<some_other_class>"
I have a page that displays products. In the encompassing <ul> I have some jQuery that adds values to attributes (such as <ul id="products" subcategorynavids="someValue">).
When a user clicks a filtering link, the jQuery checks the contents of subcategorynavids and then only displays products below that have a navid that is listed.
What I'm having an issue with is when the attribute has more than one value listed, and the user clicks the filter link a second time (to disable it), I need to remove ONLY the value that is being disabled...
For example, if the page is set to <ul id="products" subcategorynavids="9007 8019 7365"> and the user clicks the filter that enables/disables navid="8019", how do I remove the '8019' and leave the '9007' and '7365'?
I know there is .removeAttr(), .removeProp(), but those only remove the attribute ENTIRELY (right?).
I tried the following (which, as expected, didn't work)...
$("#products").attr('subcategorynavids').remove('8019');
There's no built-in jQuery way to do this, you'll have to do it manually.
$('#products').attr('subcategorynavids', function (_, val) {
return jQuery.grep(val.split(' '), function (val) {
return val !== '8019';
}).join(' ');
});
Here we use the callback way of using attr() to update an attribute. Inside the function, we split the current value val by ' ', and then filter the resulting array for those that aren't 8019 using jQuery'sgrep() function*, and the join the array back together and return it to be the new value of subcategorynavids.
* I'd want to use Array's filter() method, but it's not supported in all modern browsers, so you might as well use grep().
In this case, you could just use .replace()
var $attrs = $("#products").attr('subcategorynavids');
$("#products").attr( 'subcategorynavids', $attrs.replace( '8019', '' ));
use .replace()
$("#products").attr('subcategorynavids',$("#products").attr('subcategorynavids').replace('8019 ',''));
http://jsfiddle.net/laupkram/fg3dn/
Try this
var attr = $("#products").attr('subcategorynavids');
$("#products").attr('subcategorynavids', attr.replace('8019',''));
First get the values in that attribute and filter out the key word and again set the new attribute.. simple as that
I want to pass an array into a jQuery data attribute on the server side and then retrieve it like so:
var stuff = $('div').data('stuff');
alert(stuff[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<div data-stuff="['a','b','c']"></div>
Why does this appear to alert '[' and not 'a' (see JSFiddle link)
JSFiddle Link: http://jsfiddle.net/ktw4v/3/
It's treating your variable as a string, the zeroth element of which is [.
This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.
If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)
<div data-stuff='["a","b","c"]'> </div>
var stuff = $('div').data('stuff');
When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.
Declaring it as an attribute means that it is a string.
So stuff[0] would be equivalent to: var myString = "['a','b','c']"; alert(myString[0]);
You need to make it look like this:
<div data-stuff="a,b,c"></div>
var stuff = $('div').data('stuff').split(',');
alert(stuff[0]);
Retraction: jQuery's parsing fails because it didn't meet the rules of parseJSON.
However, I will stand behind my solution. There are aspects of the others that are less than ideal, just as this solution is less than ideal in some ways. All depends on what your paradigms are.
As others have identified the value is treated as string so it is returning "[". Please try this (aaa is the name of the div and I took out the data-stuff):
$(function(){
$.data($("#aaa")[0],"stuff",{"aa":['a','b','c']});
var stuff = $.data($("#aaa")[0],"stuff").aa;
alert(stuff[0]); //returns "a"
});
A different approach is posted at jsfiddle; var stuff = $('div').data('stuff'); stuff is a string with 0th character as '['
Well, var stuff = eval($('div').data('stuff')); should get you an array