How can I loop through an array of divs to show() them? - javascript

first post.. experienced with programming but not so much jQuery/javascript.
I have some divs that are hidden at first, and they are assigned id's in ascending order:
<script>
$(document).ready(function() {
$(".over_map").each(function(i) {
$(this).attr('id', "over_map" + (i + 1));
// console.log($(this));
});
});
</script>
Now I want to loop through a dynamic number of these divs and show them. If (eventually, not implemented yet) an SQL call returns 4 records, I would want to show() 4 of the hidden divs. Seems like this should be simple but I am missing something.. limited internet access unfortunately, but I didn't find any stack overflow entries pertaining to it.. any help appreciated!

If you have a set of elements in a jQuery object, you don't need to loop them at all - just call .show() on the set.
e.g.
$('#over_map1, #over_map3').show();
If you have a list of ids that you want to show, you can build the selector string:
function buildSelector(ids) {
var selectors = [];
for (var i = 0; i < ids.length; i++) {
selectors.push("#over-map" + ids[i]);
}
return selectors.join(", ");
}
$(document).ready(function(){
var ids = [1, 3];
$(buildSelector(ids)).show();
});
Demo at http://codepen.io/precise54/pen/nkyzg

Related

Detect a button and then press it in JavaScript

I want to make a function that would detect a button on a web page and then click it. But I want it to click a specific item.
function imready()
{
var btn = document.getElementsByClassName('text-xxxs mb-02');
for (var i = 0; i < btn.length; i++)
{
if (btn[i].innerText.indexOf('AK-47') > -1)
{
console.log('runtime');
chrome.runtime.sendMessage({ type: 'dontrun', update: 1 }, function (response) {
});
btn[i].click();
pressok();
}
}
How do I make it so that the var "btn" should equal to document.getElementsbyClassName('x') and also a different className ('y')?
Quoting from https://stackoverflow.com/a/29366682/10450049
getElementsByClassName() returns an HTMLcollection object which is similar to an array but not really an array so you can't call
array methods using the returned value. One hack is to use Array's
prototype methods along with .call()/.apply() to pass the returned
object as the context.
var elems = document.getElementsByClassName("royal") ;
var collapsedElems = document.getElementsByClassName("collapsed");
var earray = Array.prototype.slice.call(elems, 0);
var concatenated = earray.concat.apply(earray, collapsedElems) ;
console.log(concatenated)
Demo Fiddle
As far as i understand your question, you can use document.querySelector('.classX.classY') to select the needed button with both classes.
That works for the case if you only need one button on the page selected, from your code i assume exactly that.

Javascript object.id returning "undefined" in array of elements

I'm trying to get the ids of any array of elements grabbed by the class name. I've tried several different ways, all of which I believe should work, but each way returns "undefined".
example of html:
<img id='1207_image-button' class='review-button' src="..." />
javascript:
var buttons = document.getElementsByClassName("review-button");
var button;
for (button in buttons) { alert(button.id); }
I've also tried this is the for loop:
alert($(this).attr('id'));
Each way returns "undefined", i'm not sure how to alert the actual id. If I put this in the loop:
alert(button);
It will loop through and output 0 through 5 (the number of elements) then output the ids so I know then are in the array I just don't know how to get to it.
for...in loop are used to iterate over objects. Not NodeList, which is not even an array. Use a good old for loop.
for(var i = 0; i < buttons.length; i++)
alert(buttons[i].id);
By using for ... in you're incorrectly iterating through the collection of buttons. Try this, instead:
var buttons = document.getElementsByClassName("review-button");
for (var i = 0, n = buttons.length; i < n; ++i) {
var id = buttons[i].id;
...
}
or alternately, in jQuery
$('.review-button').each(function() {
var id = this.id;
...
});
Considering you are using jquery use this;
$( ".review-button" ).each(function() {
alert($( this ).attr("id"));
});
the wrong part is the loop.
You have to do:
for (button in buttons) { alert(buttons[button].id); }
in this kind of loop, you assign the index of array, not the object in each cycle.

Count all div and add each number inside span in descending order

I have this code from earlier question
$("div").each(function(i) {
$(this).find("span").text(++i);
});
-- full code in action = http://jsfiddle.net/pm3YL/
This JQuery code count every div in the page and add the order number inside span
But I need to do the same descending order
So the output will be like this one
http://jsfiddle.net/pm3YL/1/
Instead of
http://jsfiddle.net/pm3YL/
You can use this:
$($("div").get().reverse()).each(function (i) {
$(this).find("span").text(++i);
});
Demo here
Another way, using also jQuery with reverse is:
$.fn.reverse = [].reverse;
$("div").reverse().each(function (i) {
$(this).find("span").text(++i);
});
This demo here. (Thank you Ian for the suggestion.)
One more alternative is to use the length (count of elements matching that selector) and go down from there using the index of each iteration. Then you can use this:
var nr_of_divs = $("div").length;
$("div").each(function (i) {
$(this).find("span").text(nr_of_divs - i);
});
This demo here
One more, kind of related to the one above and inspired by Adeneo's answer:
var nr_of_divs = $("div").length;
$("div span").text(function (i) {
return nr_of_divs - i;
});
Demo here
$("div span").text(function(i) {
return $("div span").length-i;
});
FIDDLE
You can put something like :
var length_div = $("div").length
$("div").each(function(i) {
var tmp = length_div-i;
$(this).find("span").text(tmp);
});
You could write a for-loop that runs in reverse through the collection, but I guess it's simpler to just subtract the counter from the number of elements to get a reverse numbering:
var divs = $("div"),
l = divs.length;
divs.each(function(i) {
$(this).find("span").text(l - i);
});
(Demo)

How to refer to specific jquery ui tabs by their index such as in an array

One thought is that perhaps I should create an array and just .each() all of the tabs to create references in the manner I would like but it seems there is probably already a way to do this I just may not be aware of the scope or syntax.
For instance I have $tabs.tabs() and I want to change the AJAX URL and title of a given index such as:
for (var x = index; x < (tab_counter - 1); x++) {
$tabs.tabs(x).text(!!$tabs.tabs(x + 1).text() ? $tabs.tabs(x + 1).text() : "Deleted");
//is there a syntax to refer to tabs in this manner?
}
$tabs has been initialized as
var $tabs = $("#pages").tabs( ...
Assume that tab_counter is kept up to date (it is incremented and decremented in the add and remove events) - If I try as suggested something like
for (var x = 0; x < (tab_counter - 1); x++) { console.log($tabs.tabs.eq(x).text() + " # index " + x);
} In order to for example loop through all of the tabs titles. Is there something I am missing here in the syntax? eq() seems to be the right solution, but I suspect I am not using it right.
Solution
$tabis = $('#pages ul li a');
for (var x = 0; x < tab_counter; x++) {
console.log($tabis.eq(x).text() + " at " + x);
}
/* Prints the text label of each tab within the selected list of tabs. */
Thank you for your help dbaseman thats exactly what I was looking for. And I learned in the process so I am greatful for that
Use eq perhaps?
$tabs.eq(x).text( ... )
The tabs are all given consistently-named id attributes you could select.
One solution is to make you own function that returns objects from the IDs of each tab:
$tabs.tabs = function (index) {
return $("#tab" + index);
}
This assumes you tabs have IDs of "tab0", "tab1", etc., but it could work with any IDs.

Javascript sort not working with IE9?

the problem is I have a list with contacts and when someone change his/her status I try to move them to the top of the list. Everything worked till now, with IE9, and Firefox 4 is not working. I show you the code:
function sortByStatus()
{
var divs = getElementsByClassName(document,"status_sort");
divs.sort(compare);
for (var i = 0; i < divs.length; i++)
{
$("#contact_info").append(divs[i]);
}
}
function compare(div1, div2)
{
var id1 = div1.getAttribute("id");
var id2 = div2.getAttribute("id");
if (id1 > id2)
return 1;
else if (id1 < id2)
return -1;
else
return 0;
}
Any idea or possible fix? Thank you.
update
I have tried MrBuuBuu solution and it works patially, because now the sort by status works but the alphabetic sort is not working. I had to change part of MrBuuBuu solution, the compare function, because I compare the name of the contacts with a number just before the name that represent the status (ex. 2John , 2 means offline, and 1 online) so I have to compare with '<' and '>' and return 1, -1 or 0.
But what is worst, now it doesn't work with IE7 or IE8... the sort by status is not working.
Really weird, any idea?
document.getElementsByClassName returns a NodeList, not an array. So you have to convert it to an array first. I also cleaned up your compare() function.
function compare(div1, div2)
{
var id1 = div1.id;
var id2 = div2.id;
if (id1 < id2) {
return - 1;
}
if (id1 == id2) {
return 0;
}
return 1;
}
function sortByStatus()
{
var divs = document.getElementsByClassName("status_sort");
var divArray = $.map(divs, function(div) { return div; });
divArray.sort(compare);
$.each(divArray, function(i, div){
$("#contact_info").append(div);
});
}
If you're using the browser's native getElementsByClassName function, you may be ending up with a DOM node collection that is not a sortable Array.
When you say it's not working, are you getting any errors or is it just that the array doesn't get sorted? I'm assuming you're getting an error because sort in not defined.
One thing you could try is to clone the node collection to a plain JavaScript Array before sorting:
divs = [].slice.call(divs);
divs.sort(...
I don't have IE9 to test this, but with Chrome:
// undefined
document.getElementsByClassName("someclass").sort
But:
// the sort function
[].slice.call(document.getElementsByClassName("someclass")).sort
Are you sure it has been working? There's no such function as getElementsByClassName in the global scope.
Try using document.getElementsByClassName("status_sort") instead.

Categories