2016-03-16 14 views
5

Come trovare tutti gli elementi che hanno attributi che corrispondono al modello data-foo-bar-*, ad es.Trova un elemento che ha un attributo corrispondente a un motivo

<div data-foo-bar-id="" /> 

Utilizzando document.querySelectorAll con foo-bar-* modello dà errore:

Uncaught SyntaxError: Failed to execute 'querySelectorAll' on 'Document': '[data-foo-bar-*]' is not a valid selector.

+2

Possibile duplicato di [Trova HTML basato sull'attributo parziale] (http://stackoverflow.com/questions/12199008/find-html-based-on-partial-attribute) –

+1

@IvankaTodorova che la domanda è interamente [tag: jquery] focalizzata . – Gajus

+0

Questa risposta è già qui: http://stackoverflow.com/a/16791596/4523369 –

risposta

1

Forse l'iterazione attraverso tutti gli elementi DOM e alla ricerca di questo attributo specifico potrebbe non essere l'approccio migliore, ma qui è la mia prova:

function querySelectorPattern(regex, element) { 
    var elements = document.getElementsByTagName(element), 
    found, 
    regexp = new RegExp(regex); 
    for (var i = 0; i < elements.length; i++) { 
    var attributes = elements[i].attributes; 
    for (var k = 0; k < attributes.length; k++) { 
     if(regexp.test(attributes[k].nodeName)) { 
     console.log(elements[i]); 
     } 
    } 
    } 
} 

E una demo rapida: https://jsfiddle.net/1rsngvy8/

+0

Questa sembra una soluzione appropriata date le limitazioni dell'API DOM. – Gajus

Problemi correlati