JavaScript Javascript Traverse DOM until class is reached

You can just walk up the parent chain looking for an ancestor with the proper class. This version of the code allows there to be other class names on the object of interest so the code can be used more flexibly:

function hasClass(elem, cls) {
    var str = " " + elem.className + " ";
    var testCls = " " + cls + " ";
    return(str.indexOf(testCls) != -1) ;
}

function closest(el, cls) {
    while (el  && el !== document) {
        if (hasClass(el, cls)) return el;
        el = el.parentNode;
    }
    return null;
}

So, from your click handler, you can just do:

var id;
var target = closest(this, "section");
if (target) {
    id = target.id;
    // do whatever you want with the id
}

Working demo: http://jsfiddle.net/jfriend00/6V7HG/


FYI, a version of this code that can take any arbitrary selector is much, much more complicated as you essentially have to create a CSS selector parser and then evaluate if a given object matches all the requirements in that selector. That is probably way more work than you would want to do for this particular operation.

Usually, you're not looking up a chain for an id because you can just get the element with that id directly so I've offered a version that works with a class name. Other versions (like one that matched an attribute) could also be written.

This version is a little more generic than your particular question (returning the target element rather than the target id) which allows you to use it in more circumstances. If you really just want a function that returns the target id, that can be done like this:

function closest(el, cls) {
    while (el  && el !== document) {
        if (hasClass(el, cls)) return el.id;
        el = el.parentNode;
    }
    return null;
}
Answer:1

You can just use Element.closest():

let closestElement = document.getElementById('click').closest('.section');

Here is a snippet to show it in action:

console.log(document.getElementById('click').closest('.section').id);
<div id="hooray" class="section">
   <div>
      <div>
        <div id="click">click</div>
      </div>
   </div>
 </div>
Answer:2

How can I partially sort an array in JavaScript, based on some conditions that I choose? Given an array var tab = [ {html: 'This is a test'}, {html: 'Locked item', locked: true}, {html:...

How can I partially sort an array in JavaScript, based on some conditions that I choose? Given an array var tab = [ {html: 'This is a test'}, {html: 'Locked item', locked: true}, {html:...

  1. sort partially sorted array
  2. c++ partial sort an array
  3. best sort for partially sorted array
  4. sorting partially sorted array

I am new to google api. I am able to do this file upload from app script and any file which is uploaded through that script get stored to my drive only. But how to do this using javascript. Example ...

I am new to google api. I am able to do this file upload from app script and any file which is uploaded through that script get stored to my drive only. But how to do this using javascript. Example ...

  1. upload file google drive
  2. upload file google colab
  3. upload file google form
  4. upload file google drive api
  5. upload file google cloud storage
  6. upload file google drive python
  7. upload file google doc
  8. upload file google app script
  9. upload file google storage
  10. upload file google drive php
  11. upload file google sheets
  12. upload file google drive c#
  13. upload file google sites
  14. upload file google cloud storage nodejs
  15. upload file google drive java
  16. upload file google drive android
  17. upload file google drive mobile
  18. upload file google translate

I have a large JSON file with a snippet of the file below. Please ignore the values as they are only used as placeholders for this question. "restaurants":[ "name": "Burger King", ...

I have a large JSON file with a snippet of the file below. Please ignore the values as they are only used as placeholders for this question. "restaurants":[ "name": "Burger King", ...

  1. jquery iterate through array
  2. jquery iterate through elements
  3. jquery iterate through table rows
  4. jquery iterate through json
  5. jquery iterate through child elements
  6. jquery iterate through select options
  7. jquery iterate through json array
  8. jquery iterate through array of objects
  9. jquery iterate through list
  10. jquery iterate through checkboxes
  11. jquery iterate through elements with same class
  12. jquery iterate through json data
  13. jquery iterate through find results
  14. jquery iterate through class elements
  15. jquery iterate through table
  16. jquery iterate through table columns
  17. jquery iterate through li
  18. jquery iterate through table header
  19. jquery iterate through class items
  20. jquery iterate through all options select

I have three sliding panels in my html. The thing is that panels overlay each other when open. I would like to get a function that create an event when one panel (eg. #panel1) is open already and the ...

I have three sliding panels in my html. The thing is that panels overlay each other when open. I would like to get a function that create an event when one panel (eg. #panel1) is open already and the ...

  1. jquery sliding panels
  2. jquery sliding panel demo
  3. jquery sliding panel left to right
  4. jquery sliding panel from right
  5. jquery sliding panel from left
  6. jquery ui sliding panel
  7. jquery vertical sliding panel
  8. jquery mobile sliding panel
  9. jquery sliding sidebar panel
  10. jquery create sliding panel
  11. jquery sliding overlay panel
  12. jquery sliding menu panel
  13. jquery lateral sliding panel
  14. jquery side sliding panel plugins
  15. jquery side sliding panel