2009-04-23 10 views

Respuesta

15

navegadores modernos: (IE9 +)

//slice turns the resulting DOM collection into a proper array 
var matches = [].slice.call(document.querySelectorAll('[id^=log_]'));

jQuery:

$('[id^=log_]') 

navegadores antiguos, sin jQuery:

var matches = []; 
var elems = document.getElementsByTagName("*"); 
for (var i=0; i<elems.length; i++) { 
    if (elems[i].id.indexOf("log_") == 0) 
    matches.push(elems[i]); 
} 
//matches now is an array of all matching elements. 
+2

Y si no se está usando jQuery? : P –

+1

@Daniel, consulte la actualización anterior. – Tracker1

+2

Su selector jQuery podría mejorarse. El "selector de estrellas" es implícito, debe usar el selector "starts-with" en lugar de "contains", y no es necesario que el guión bajo escape: '$ (" [id^= log _] ")' –

-1

Se sería mejor usar un JS framework para lograr esto porque tienen funciones avanzadas de selector DOM que hacen que lo que quieres hacer sea increíblemente fácil. Hay muchos para elegir, pero los más populares son jQuery, Prototype, MooTools y Dojo.

3

Ok, aquí está una respuesta JavaScript recta:

// a handy function to aid in filtering: 
// takes an array and a function, returns another array containing 
// only those elements for which f() returns true 
function filter(a, f) 
{ 
    var ret = []; 
    for (var i=0; i<a.length; ++i) 
    { 
    if (f(a[i])) 
     ret.push(a[i]); 
    } 
    return ret; 
} 

// this collects all elements in the current document 
var elements = document.getElementsByTagName("*"); 

// and this filters out all but those that match our pattern 
var logElements = filter(elements, function(el) 
    { return /log_/.test(el.id) }); // simple expression 
Cuestiones relacionadas