Element.matches()
O método Element.matches()
retorna verdadeiro se o elemento puder ser selecionado pela sequência de caracteres específica; caso contrário retorna falso.
Diversos navegadores implementam isto, prefixado, sob nome não padronizado matchesSelector()
.
Sintaxe
var result = element.matches(selectorString);
result contém o valor de retorno true ou false.
selectorString
é uma string representando o seletor para teste.
Exemplo
<ul id="birds">
<li>Orange-winged parrot</li>
<li class="endangered">Philippine eagle</li>
<li>Great white pelican</li>
</ul>
<script type="text/javascript">
var birds = document.getElementsByTagName('li');
for (var i = 0; i < birds.length; i++) {
if (birds[i].matches('.endangered')) {
console.log('The ' + birds[i].textContent + ' is endangered!');
}
}
</script>
Isto irá logar "The Philippine eagle is endangered!" para o console, desde que o elemento tenha de fato um atributo de classe com o valor endangered
.
Exceções
SYNTAX_ERR
- O seletor de string específico é inválido.
Polyfill
Para navegadores que não suportam Element.matches()
ou Element.matchesSelector()
, mass possuem suporte para document.querySelectorAll()
, existe um polyfill:
if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) {} return i > -1; }; }
Especificação
Especificação | Status | Comentário |
---|---|---|
DOM The definition of 'Element.prototype.matches' in that specification. |
Padrão em tempo real | Initial definition |
Compatibilidade de navegador
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Original support with a non-standard name |
(Yes)[1] |
3.6 (1.9.2)[2] | 9.0[3] | 11.5[4] 15.0[1] |
5.0[1] |
Specified version | 34 | 34 (34) | ? | 21.0 | 7.1 |
Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Original support with a non-standard name | ? | 1.0 (1.9.2)[2] | ? | ? | ? |
Specified version | ? | 34.0 (34) | ? | ? | 8 |
[1] Esta feature foi implementada com o nome não padronizado webkitMatchesSelector
.
[2] Esta feature foi implementada com o nome não padronizado mozMatchesSelector
. Anteriormente para o Gecko 2.0, seletores de string inválido faziam com que retornasse false ao invés de empurrar uma exceção.
[3] Esta feature foi implementada com o nome não padronizado msMatchesSelector
.
[4] Esta feature foi implementada com o nome não padronizado oMatchesSelector
.