简体   繁体   中英

Javascript get more than one id at a time

I'm just wondering if its possible in javascript to get more than one id at a time, without the use of JQuery. I'm checking the background color of each cell in a dynamically created table. For instance, I have this code:

var black = "rgb(0, 0, 0)";
if(document.getElementById("cell1").style.backgroundColor == black &&
   document.getElementById("cell2").style.backgroundColor == black)
{
  alert("Two cells are black!");
}

Would it be possible to do something like this:

var black = "rgb(0, 0, 0)";
if(document.getElementById("cell1","cell2").style.backgroundColor == black)
{
  alert("Two cells are black!");
}

I'm trying not to use JQuery at all as I'm not too familiar with it.

With modern browsers you can do something similar using querySelectorAll ( compatibility matrix ), but you'd still have to loop over the resulting NodeList :

var nodes = document.querySelectorAll("#cell1, #cell2");
var count = 0;
for (var index = 0; index < nodes.length; ++index) {
    if (nodes[index].style.backgroundColor == black) {
        ++count;
     }
}
if (nodes.length === count) {
    alert("Both are black");
}

Doesn't really buy you anything over, say:

var cells = ["cell1", "cell2"];
var count = 0;
for (var index = 0; index < cells.length; ++index) {
    if (document.getElementById(cells[index]).style.backgroundColor == black) {
        ++count;
    }
}
if (cells.length === count) {
    alert("All cells are black");
}

So in short: No, there isn't really anything more useful you can do.

No, without using jQuery or other javascript helper libraries.

querySelector is not supported by IE7 and below which still represents a fairly large proportion of the traffice http://caniuse.com/#feat=queryselector

Not natively. You could write your own fairly easily, though:

function getElementsById(elements)
{
    var to_return = [ ];
    for(var i = 0; i < elements.length; i++)
    {
        to_return.push(document.getElementById(elements[i]));
    }
    return to_return;
}

This will accept an array of IDs as the parameter, and return the elements in an array. You might also want to look into the document.querySelector method.

I have upvoted @BenM's answer, but I'd like to suggest another option.

Your issue:

I'm checking the background color of each cell

In this case, it would make more sense to attach the id to the table itself. Your selector becomes (assuming no nested table):

var cells = document.getElementById("myTable").getElementsByTagName("td");

or for recent browsers:

var cells = querySelectorAll("#myTable>tbody>tr>td");

For the record, here is another way if all your cells have a similar id "cellxxx":

var cells = querySelectorAll("td[id^='cell']");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM