Finding Closest Element Without Jquery

Finding closest element without jQuery

Little (very) late to the party, but nonetheless. This should do the trick:

function closest(el, selector) {
var matchesFn;

// find vendor prefix
['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) {
if (typeof document.body[fn] == 'function') {
matchesFn = fn;
return true;
}
return false;
})

var parent;

// traverse parents
while (el) {
parent = el.parentElement;
if (parent && parent[matchesFn](selector)) {
return parent;
}
el = parent;
}

return null;
}

querySelector to select closest ancestor without jQuery

You're almost there, but if you don't want the element you initially selected to be a possible result, you'll have to call closest on its parent, not on the selected element.

console.log(document.querySelector("#myselector").parentElement.closest(".card").id);
.card {  background: green;}
<div class="card">  inside first  <div class="card" id="tryingtoselectthis">    inside second    <div class="card" id="myselector">      inside third    </div>  </div></div>

How to get the id of closest input text without jquery?

It should be easy if they're always siblings like that.

var nextInputId = buttonClicked.nextSibling.id;

jsFiddle.

This is fragile and not recommended for anything but a very simple set of limited markup.

Unfortunately, nextElementSibling isn't available until IE9, so if you have a text node there (even some whitespace), you're in for some pain.

A pretty good solution that is relatively robust would be...

var node = buttonClicked;
var nextInputId = null;

while (node = node.nextSibling) {
if (node.tagName && node.tagName.toLowerCase() == "input") {
nextInputId = node.id;
break;
}
}

jsFiddle.

Selecting a parent element (without using Jquery)

That's what parentNode is for:

a.parentNode.querySelectorAll('.divA');

closest() not selecting the element

closest() get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. You are looking for an element which is not related with button.js-show-code.

Try

 $('.js-show-code').click(function(){
$(this).closest('h2').next(".grid-100").find("code").slideToggle()
});

Here is the fiddle

Find closest element in complete document

Use .prevUntil('.class'), .nextUntil('.class'), .parentsUntil('.class'), then compare their sizes.

Whichever one has the least size is the closest to the element in terms of DOM structure.

UPDATE: In the process, you will also need .andSelf(), .filter() and typical .next() and .prev() to actually get to the target you want. Demo has been updated. You can see that now the code is more generic.

You'll probably need a sorting function too, as I've did in the proof-of-concept below.

DEMO: http://jsfiddle.net/terryyounghk/FzA78/

Side-note: There's no .childrenUntil(), because that's branching outwards the DOM tree, not inwards towards the document root, in case you're wondering. But my guess is, you could do a $('.me').find('.class') first, then for each of them, do a .parentsUntil('.me') instead, then compare the sizes. I'm not sure if this would work though.

Jquery find nearest matching element

var otherInput = $(this).closest('.row').find('.inputQty');

That goes up to a row level, then back down to .inputQty.

Find the closest ancestor element that has a specific class

Update: Now supported in most major browsers

document.querySelector("p").closest(".near.ancestor")

Note that this can match selectors, not just classes

https://developer.mozilla.org/en-US/docs/Web/API/Element.closest


For legacy browsers that do not support closest() but have matches() one can build selector-matching similar to @rvighne's class matching:

function findAncestor (el, sel) {
while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel)));
return el;
}


Related Topics



Leave a reply



Submit