<div class="logo">
<span>JS</span> <span>ElementsMatch</span>
<div>Native JS extension to match elements</div>
</div>
<p>
Matching an element against a selector, another element or a collection of elements
</p>
<div>
The solution is implemented at the <code>Element.prototype</code> level, available on all the major browsers, supported even in IE, since the 8.x version.<br />
Usage is:
<pre>
var elem = document.getElementById('hello');
elem.is('div');
elem.is('.banner');
elem.is('#mainButton');
elem.is(document.getElementsByTagName('span'));
</pre>
Elements to match (check the console for the output):
</div>
<div id="a">div #a</div>
<div id="b">div #b</div>
<div id="c">div #c</div>
<div id="d">div #d</div>
Element.prototype.is = function(match) {
// match is string selector or an element or an array or elements
if (match.nodeType) {
return this === match;
}
var qa = (typeof(match) === 'string' ? document.querySelectorAll(match) : match),
length = qa.length,
returnArr = [];
while (length--) {
if (qa[length] === this) {
return true;
}
}
return false;
}
var a = document.getElementById('a'),
b = document.getElementById('b'),
c = document.getElementById('c'),
d = document.getElementById('d');
console.log(b.is(b)); //true
console.log(b.is(d)); //false
console.log(b.is([c, d, b])); //true
console.log(b.is('#b')); //true
console.log(b.is('.b')); //false
console.log(b.is(document.querySelectorAll('div'))); //true
console.log(b.is('div')); //true
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.