JSFiddle - React, Tailwind, and code Playground

by drzaus

HTML

<div id="out"></div>

<div id="1" class="class1" style="display:none">
	<div id="2" class="inside_class1">
		<div class="mode class names asd">
			<div><div><div><div><div><div class="class"><div id="id"><div class="asd class another-class underscore_class">
				<div class="just-adding alot-of classes so that the"><div class="test will be"><div class="of reasoniable"><div id="size">
					<ul><li><ol><li>
						<div class="la le lu lee lo"><div id="idagain">
							<ul><li><span><a href="#" id="link">Link</a></span></li></ul>
						</div></div>
					</li></ol></li></ul>
				</div></div></div></div>
			</div></div></div></div></div></div></div></div>
		</div>
	</div>
</div>

CSS

#out {
  font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace;
}

JavaScript

!(function($, undefined) {
	/// adapted from http://stackoverflow.com/a/15623322/1037948
	
	get_selector = function(element, delim) {
		delim = delim || ' > ';
		pieces = [];
		if (typeof element.tagName !== typeof undefined) {
		do {
			if (element.className) {
			var classes = element.className.split(' ')
			for (var i in classes) {
				if(classes.hasOwnProperty(i)) {
					pieces.unshift(classes[i]);
					pieces.unshift('.');
				}// hasOwnProperty
			}// foreach classes
			}// if className
			if (element.id) {
			pieces.unshift(element.id);
			pieces.unshift('#');
			}// if id
			// for some reason I'm seeing "undefined" here in Chrome...strip empty items later
			pieces.unshift(element.tagName);
			pieces.unshift(delim);
		} while(element = element.parentNode);
		}// if tagname
		// strip the "empty entries"
		return pieces.slice(3).join('');
	};

	$.fn.getSelector = function(only_one, delim) {
		delim = (delim || (typeof only_one === typeof true ? false : only_one) || ' > ');
		
		if (true === only_one) {
			return get_selector(this[0], delim);
		} else {
			return $.map( this, function(el) {
				return get_selector(el, delim);
			});
		}
	};

})(window.jQuery);

$('#out')
    .html('The selector of the {#link, #id} is: <h1>Default Config</h1>')
    .append($('#link, #id').getSelector().join('<hr />'))
    .append('<h1>Custom Delimiter</h1>')
    .append( $('#link, #id').getSelector(' || ').join('<hr />') )
    .append('<h1>First only with Custom Delimiter</h1>')
    .append( $('#link, #id').getSelector(true, ' % ') )
    
;