jQuery Common Ancestor
HTML
<div id="outer">
<dl>
<dt>Items:</dt>
<dd>
<ul>
<li>Item 1<div class="item-info">...</div></li>
<li>Item 2<div class="item-info">...</div></li>
<li>Item 3<div class="item-info">...</div></li>
</ul>
</dd>
</dl>
<p><br></p>
<h2 id="h2">Enter a selector and click Find</h2>
<p>
<br>
<label for="selector">Selector:</label> <input type="text" id="selector" name="selector" size=50><br>
Presets: <input type="button" class="input" value="List Items" data-selector=".item-info">
<input type="button" class="input" value="List + input + h2" data-selector=".item-info, #ancestor, #h2"><br>
<br>
<input type="button" id="go" value="Find"><br>
<label for="ancestor">Ancestor:</label> <input type="text" id="ancestor" name="ancestor" size="50">
</p>
</div>
JavaScript
jQuery.fn.commonAncestor = function() {
var parents = [];
var minlen = Infinity;
$(this).each(function() {
var curparents = $(this).parents();
parents.push(curparents);
minlen = Math.min(minlen, curparents.length);
});
for (var i in parents) {
parents[i] = parents[i].slice(parents[i].length - minlen);
}
// Iterate until equality is found
for (var i = 0; i < parents[0].length; i++) {
var equal = true;
for (var j in parents) {
if (parents[j][i] != parents[0][i]) {
equal = false;
break;
}
}
if (equal) return $(parents[0][i]);
}
return $([]);
}
function displayAncestor() {
var ancestor,
selector = $('#selector').attr('value');
if (selector === '') {
window.alert('Please enter a jQuery selector and try again.');
return;
}
ancestor = $(selector).commonAncestor();
if (ancestor.length === 0) {
$('#ancestor').attr('value', 'no common ancestor found');
} else {
$('#ancestor').attr('value', ancestor[0].tagName);
}
};
$('#go').on('click', displayAncestor);
$('input.input:button').on('click', function() {
$('#selector').attr('value', $(this).data('selector'));
displayAncestor();
});