cross browser remove element from an array - javascript

I have an array of numbers which are values of the data-cardNumber attribute of different element in my site.
I'm trying to remove the value of the data-cardNumber attribute of the element that has that attribute that also has the class .lastBeenDragged.
I am trying this, but I think I may have oversimplified my code too much.
When I console.log the array before and after executing this code there is no change in the array.
How can I properly and cross browserly remove an element, the value of the data-cardNumber of the element with the class .lastBeen Dragged, from the array swipedAwayCards ?
Here is the code:
if(swipedAwayCards.indexOf($('.lastCardDragged').attr('data-cardNumber')) > -1) swipedAwayCards.splice(swipedAwayCards.indexOf($('.lastCardDragged').attr('data-cardNumber')), 1);

Since Array.indexOf() is not supported crossbrowser, you can user $.inArray()
var index = $.inArray($('.lastCardDragged').attr('data-cardNumber'), swipedAwayCards);
if (index > -1) {
swipedAwayCards.splice(index, 1);
}

Try this :
var v = $('.lastCardDragged').attr('data-cardNumber');
for (var i = 0, l = swipedAwayCards.length; i < l; i++) {
if (swipedAwayCards[i] == v) {
swipedAwayCards.splice(i, 1);
break;
}
}

Related

JS: inserting element into array

I have the following function. It is expected to insert item into array at position no. When item is inserted, the last element of the array is dropped, i.e. array must always have the same length. Array is taken from string session variable itemstr using split(). The very first element of the array is to be never changed, so I always call this function starting with n===1. The problem is that the function doesn't insert in the sense of splice(). It simply changes the value of element #no
function insert_into_array(no, item)
{
var itemarr = sessionStorage.itemstr.split(',');
if ((no < itemarr.length) && (no > 0)) {
var i;
for (i === itemarr.length - 1; i > no; i--) {
itemarr[i] = itemarr[i - 1];
}
itemarr[no] = item;
sessionStorage.itemstr = itemarr.toString();
}
}
In this line you have a type:
for (i === itemarr.length - 1; i > no; i--) {
It should be actually: i = itemarr.length - 1 and not i === itemarr.length - 1
Not getting what you exactly want.. What i understand is that you need to insert element at position defined by no and remove last element. You can try this in case..
function insert_into_array(no, item)
{
var itemarr = sessionStorage.itemstr.split(',');
if ((no < itemarr.length) && (no > 0)) {
itemarr .splice(no, 0, item); //Insert element at position defined by #no
itemarr .pop(); //removes last element
}
sessionStorage.itemstr = itemarr.toString();
}
Culprit for your function is following line
for (i === itemarr.length - 1; i > no; i--)
here i will be assigned to the value undefined since this is a comparison(===) and not assignment (=). Thus i(undefined) > no will always be false , so no more loop execution.
Simply replace comparison with assignment
for (i = itemarr.length - 1; i > no; i--)
As i understood from the question, you want to insert a variable to an array at a fixed position,and previous content at that position need to shifted and last array value need to be removed.
just use arr.pop() to remove last element and make use of a for loop to shift one position to right.
using jQuery will be more simple here.

Find all elements containing a value in an attribute

I use this to take some attributes:
window.document.getElementsByClassName("atbk")
However the class atbk is used in different elements. I would like to keep the attributes which only have in their href a common word /url
I tried this:
window.document.getElementsByClassName("atbk").href.indexOf("/url")
but it is not helpful. Is there anything I could do?
You can use the css selector [href*="/url"] to select elements containing a substring in an attribute.
window.document.querySelectorAll('.atbk[href*="/url"]');
Try this:
var list = window.document.getElementsByClassName("atbk");
var newlist =[];
for (z = 0; z < list.length; z++)
{
if (list[z].href.indexOf('/url') > -1)
{
newlist.push(list[z]);
}
}
// use newlist...

Loop through array and match items to html elements

I am looking for a more intuitive way to run the code below (as it is also incomplete to my purpose).
for (j = 0; j<items.length; j++) {
var indivItem = items[j];
if (indivItem.category == 1) {
$('.indiv_category[idnumber="1"]').append('<ul class="left_side_item"><li>'+indivItem.title+'</li></ul>');
}
else if (indivItem.category == 2) {
$('.indiv_category[idnumber="2"]').append('<ul class="left_side_item"><li>'+indivItem.title+'</li></ul>');
}
}
Essentially I need line 3 to check if (indivItem.category > 0) then look for the element with a matching idnumber attribute and append the necessary info.
I need this continue for the length of available .indiv_category elements.
Basically a matchup of the all items in the 'items' array to all of the elements with a matching 'idnumber' attribute to the item in the array that contains the same id number.
Remmove the condition and just use the variable items[j].category in selector.
for (j = 0; j<items.length; j++) {
$('.indiv_category[idnumber="'+ items[j].category + '"]').append('<ul class="left_side_item"><li>'+indivItem.title+'</li></ul>');
}

document.getElementsByClassName exact match to class

There are two similar classes - 'item' and 'item one'
When I use document.getElementsByClassName('item') it returns all elements that match both classes above.
How I can get elements with 'item' class only?
The classname item one means the element has class item and class one.
So, when you do document.getElementsByClassName('item'), it returns that element too.
You should do something like this to select the elements with only the class item:
e = document.getElementsByClassName('item');
for(var i = 0; i < e.length; i++) {
// Only if there is only single class
if(e[i].className == 'item') {
// Do something with the element e[i]
alert(e[i].className);
}
}
This will check that the elements have only class item.
Live Demo
document.querySelectorAll('.item:not(.one)');
(see querySelectorAll)
The other way is to loop over the what document.getElementsByClassName('item') returns, and check if the one class is present (or not):
if(element.classList.contains('one')){
...
}
You're going to want to make your own function for exact matches, because spaces in a class means it has multiple classes. Something like:
function GetElementsByExactClassName(someclass) {
var i, length, elementlist, data = [];
// Get the list from the browser
elementlist = document.getElementsByClassName(someclass);
if (!elementlist || !(length = elementlist.length))
return [];
// Limit by elements with that specific class name only
for (i = 0; i < length; i++) {
if (elementlist[i].className == someclass)
data.push(elementlist[i]);
}
// Return the result
return data;
} // GetElementsByExactClassName
You can use Array.filter to filter the matched set to be only those with class test:
var elems = Array.filter( document.getElementsByClassName('test'), function(el){
return !!el.className.match(/\s*test\s*/);
});
Or only those with test but not one:
var elems = Array.filter( document.getElementsByClassName('test'), function(el){
return el.className.indexOf('one') < 0;
});
(Array.filter may work differently depending on your browser, and is not available in older browsers.) For best browser compatibility, jQuery would be excellent for this: $('.test:not(.one)')
If you have jQuery, it can be done using the attribute equals selector syntax like this: $('[class="item"]').
If you insist on using document.getElementsByClassName, see the other answers.

Javascript getElementById based on a partial string

I need to get the ID of an element but the value is dynamic with only the beginning of it is the same always.
Heres a snippet of the code.
<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite">
The ID always starts with poll- then the numbers are dynamic.
How can I get the ID using just JavaScript and not jQuery?
You can use the querySelector for that:
document.querySelector('[id^="poll-"]').id;
The selector means: get an element where the attribute [id] begins with the string "poll-".
^ matches the start
* matches any position
$ matches the end
jsfiddle
Try this.
function getElementsByIdStartsWith(container, selectorTag, prefix) {
var items = [];
var myPosts = document.getElementById(container).getElementsByTagName(selectorTag);
for (var i = 0; i < myPosts.length; i++) {
//omitting undefined null check for brevity
if (myPosts[i].id.lastIndexOf(prefix, 0) === 0) {
items.push(myPosts[i]);
}
}
return items;
}
Sample HTML Markup.
<div id="posts">
<div id="post-1">post 1</div>
<div id="post-12">post 12</div>
<div id="post-123">post 123</div>
<div id="pst-123">post 123</div>
</div>
Call it like
var postedOnes = getElementsByIdStartsWith("posts", "div", "post-");
Demo here: http://jsfiddle.net/naveen/P4cFu/
querySelectorAll with modern enumeration
polls = document.querySelectorAll('[id ^= "poll-"]');
Array.prototype.forEach.call(polls, callback);
function callback(element, iterator) {
console.log(iterator, element.id);
}
The first line selects all elements in which id starts ^= with the string poll-.
The second line evokes the enumeration and a callback function.
Given that what you want is to determine the full id of the element based upon just the prefix, you're going to have to do a search of the entire DOM (or at least, a search of an entire subtree if you know of some element that is always guaranteed to contain your target element). You can do this with something like:
function findChildWithIdLike(node, prefix) {
if (node && node.id && node.id.indexOf(prefix) == 0) {
//match found
return node;
}
//no match, check child nodes
for (var index = 0; index < node.childNodes.length; index++) {
var child = node.childNodes[index];
var childResult = findChildWithIdLike(child, prefix);
if (childResult) {
return childResult;
}
}
};
Here is an example: http://jsfiddle.net/xwqKh/
Be aware that dynamic element ids like the ones you are working with are typically used to guarantee uniqueness of element ids on a single page. Meaning that it is likely that there are multiple elements that share the same prefix. Probably you want to find them all.
If you want to find all of the elements that have a given prefix, instead of just the first one, you can use something like what is demonstrated here: http://jsfiddle.net/xwqKh/1/
I'm not entirely sure I know what you're asking about, but you can use string functions to create the actual ID that you're looking for.
var base = "common";
var num = 3;
var o = document.getElementById(base + num); // will find id="common3"
If you don't know the actual ID, then you can't look up the object with getElementById, you'd have to find it some other way (by class name, by tag type, by attribute, by parent, by child, etc...).
Now that you've finally given us some of the HTML, you could use this plain JS to find all form elements that have an ID that starts with "poll-":
// get a list of all form objects that have the right type of ID
function findPollForms() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
results.push(list[i]);
}
}
return(results);
}
// return the ID of the first form object that has the right type of ID
function findFirstPollFormID() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
return(id);
}
}
return(null);
}
You'll probably have to either give it a constant class and call getElementsByClassName, or maybe just use getElementsByTagName, and loop through your results, checking the name.
I'd suggest looking at your underlying problem and figure out a way where you can know the ID in advance.
Maybe if you posted a little more about why you're getting this, we could find a better alternative.
You use the id property to the get the id, then the substr method to remove the first part of it, then optionally parseInt to turn it into a number:
var id = theElement.id.substr(5);
or:
var id = parseInt(theElement.id.substr(5));
<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite" target="_blank">
The ID always starts with 'post-' then the numbers are dynamic.
Please check your id names, "poll" and "post" are very different.
As already answered, you can use querySelector:
var selectors = '[id^="poll-"]';
element = document.querySelector(selectors).id;
but querySelector will not find "poll" if you keep querying for "post": '[id^="post-"]'
If you need last id, you can do that:
var id_list = document.querySelectorAll('[id^="image-"]')
var last_id = id_list.length
alert(last_id)

Categories

Resources