2009-04-23 10 views

Odpowiedz

15

nowoczesnych przeglądarek: (IE9 +)

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

jQuery:

$('[id^=log_]') 

starymi przeglądarkami, bez 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

A jeśli nie używasz jQuery? : P –

+1

@ Daniel, patrz aktualizacja powyżej. – Tracker1

+2

Twój selektor jQuery mógłby zostać ulepszony. "Gwiazdowy selektor" jest niejawny, powinieneś używać selektora "uruchamiającego" zamiast "zawiera", a podkreślenie nie potrzebuje ucieczki: '$ (" [id^= log _] ")' –

-1

It Najlepiej byłoby użyć do tego celu JS framework, ponieważ mają one zaawansowane funkcje selektora DOM, dzięki którym to, co chcesz zrobić, jest niezwykle łatwe. Istnieje wiele opcji do wyboru, ale bardziej popularne są: jQuery, Prototype, MooTools i Dojo.

3

Ok, oto prosta odpowiedź JavaScript:

// 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 
Powiązane problemy