Add each div attributes in an array - javascript

I am trying to build an array containing some data-attributes that a div have. It looks like this.
<div class="myclass" data-test="hello"></div>
I've come this far, but not sure how to continue:
$('#container .myclass').each(function () { mArray. })
I have no idea what to with the array...
And the output I am looking for is
array 0
... test = hello...
or something like that.
I guess I could take all ITEMS by just writing them and adding, but it seems like there should be an easier way of doing so.

data() returns an object containing all the data attributes. Could that be something?
$('#container .myclass').data()

If your div has attributes beginning with the data-prefix (data-test="hello" data-info="some text.." and so on), you can store the values of all these attributes in an object with the jQuery data method, for example like this:
var myObject = $("div.myclass").data();

This is one possible solution , using map(): DEMO HERE
var dataTests =$('#container .myclass').map(function(){
return this.getAttribute('data-test');
}).get();
alert(dataTests[0]);//element 0

Related

AngularJS/JavaScript Remove specific element from Localstorage array

I have an array in my LocalStorage that I manipulate with ngStorage.
I am trying to remove items from there but when I use
$localStorage.someArrayName.splice(id, 1);
only the first removed item works fine, then removing stop working as I would like to.
I also tried something like this:
if (id === $localStorage.someArrayName.length) {
$localStorage.someArrayName.pop();
}
else if (id === 0) {
$localStorage.someArrayName.shift();
}
else {
$localStorage.someArrayName.splice(id, 1);
}
But I get even more buggy result
I tried from the example in https://github.com/gsklee/ngStorage like this:
delete $localStorage.someArrayName[id];
but it deletes the values and I get null,null,null values in my local storage array. And then I even get ng repeat error about duplicate values:
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed...
I cannot handle it. I am not sure if it's some small issue or I am doing something fundamentally wrong. Can you give me some guidance? Thank you in advance!
This is how my array looks like saved in the localstorage:
[{"content":"something"},{"content":"else"}] //etc...
So you are using ng-repeat for something and your ids are there. If you use $index as value for your id parameter when you remove at item from the array, your array numbering is not longer the same and the id is not what you expect to be.
You also do not need the pop() and shift() methods.
Asuming your ng-repeat is something like this:
<element ng-repeat="item in someThing">
{{item.prop}} <childelem ng-click=delete($index)>delete</childelem>
</element>
and if your function is:
$scope.delete = function (id) {
$localStorage.someArrayName.splice(id, 1);
};
Then you would need something like this:
<element ng-repeat="item in someThing">
{{item.prop}} <childelem ng-click=delete(item)>delete item</childelem>
</element>
and:
$scope.delete = function (item) {
$localStorage.someArrayName.splice($localStorage.someArrayName.indexOf(item), 1);
};
and this is going to remove the entire {"content":"something"}
from your array.
No idea if this is the right direction of the problem and if this is the scenario, but I hope it will help you. Best regards!

Jquery if string matches value in array

The product page on my website displays the #productID within a string i.e "Product ID: 743961". Using jQuery I want to take this #productID string and compare it to the array of IDs. If the #productID matches an ID within the array I want to append a message.
<div id="productID"> Product ID: 743961 </div>
I was initially trying to do the following, but was struggling to get the desired results.
var myArray = [ 743961, 743963, 743965 ];
$( "#prod_code:contains('myArray')" ).css( "text-decoration", "underline" );
My array has over 2,000 items, so this may not be the best solution. I am aware that Ajax would be the best solution, but am unable to use it in this instance.
With such a large array it sounds like AJAX would be a better solution. However, if you must use this pattern, you would first need to grab the productId value from the text of the element and then you can determine if it exists in the array. Something like this:
var productId = $.trim($('#productID').text().split(':')[1]);
if ($.inArray(productId, myArray) >= 0)
$('#prod_code').css('text-decoration', 'underline');
This is obviously a rather simple example, you would most likely need more validation on the extraction of the productId to make it more robust.

Getting elements from array by class

I have a list of list items that i get like this:
var searchResultItems = $(resultContainerId + ' li');
The search result items can have different classes. How can i get all items of a certain class from the searchResultItems? Im looking for something like:
var highPriorityItems = searchResultItems.find('.highPriority');
I know find() does not work in this situation because it goes through child elements. I am hoping there is something similar what im looking for.
The .filter method can do exactly what you want if substituted for .find in your example.

Working with Data Attributes - Build a List & See if One Exists

I have 2 questions based on the graphic below:
How can I tell if one of the 'data-conversationmessageuserid' data attributes with a specific value exists - say 1000000003? I believe data selectors is what I need and have tried the following but its not working yet:
if($('#conversationsInBoxMessagesWrapperDIV')['data-conversationmessageuserid=1000000003']) {
// do something
}
How could I get all the 'data-conversationmessageuserid' data attributes into an array and the loop through them? I'm still playing with this code but its far from publishable. Trying to use .map
.map(function()
thankyou so much
Try:
if($('#conversationsInBoxMessagesWrapperDIV [data-conversationmessageuserid=1000000003]').length)
or
$('#conversationsInBoxMessagesWrapperDIV').find('[data-conversationmessageuserid=1000000003]') //Or children only to look at one level.
To get all the data values you could do:
var conversationmessageuserids = $('#conversationsInBoxMessagesWrapperDIV').children().map(function(){
return $(this).data('conversationmessageuserid');
}).get();
jQuery supports data attributes: http://api.jquery.com/data/
So you could do if($('#conversationsInBoxMessagesWrapperDIV').data('conversationmessageuserid') === 1000000003)

How to append values to the custom data stored in an element

Let's say I want to store some custom value in a element, I would need:
$('div').data('k','v');
But now I need to add more data to that element: v2.
The only way I could come up with is to somehow store or reference the previous data, and append to it, but it doesn't look like the best way to do it nor the most efficient:
$('div').data('k','v');
var prevData = $('div').data('k');
$('div').data('k',prevData + ',v2');
alert($('div').data('k'));
This will alert v,v2 as it should, but is this the correct approach?
You can use lists as data attributes:
$('.selector').data('test', []);
var list = $('.selector').data('test');
list.push('foo')
It's pretty useful, also because you can fill data- attributes with JSON in the HTML at page generation time, and .data() will automatically convert them to normal JS objects.
if you are using array as data atribute, you can do this
$('.selector').data('list', []);
$('.selector').data('list').push(1);
$('.selector').data('list').push(2);
$('.selector').data('list'); // Will return [1,2]

Categories