3

Сейчас, чтобы найти нужного мне предка, я пишу elem.parentElement.parentElement.parentElement.parentElement.

1) А можно как-то поизящнее?

2) И другой вопрос: есть такая структура:

<table id="some">
    <tbody>
        <tr><td><input id="myInput" type="text"></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
    </tbody>
<table>

Как узнать id table (в данном случае это "some"), если известен input#myInput? Спасибо!

1
  • 1
    Можно написать цикл. Но вообще зависит от задачи. И при правильном подходе задача найти родителя не то что бы часто нужна
    – Alexey Ten
    15 июл 2019 в 12:52

4 ответа 4

4
let elem = document.getElementById("myInput");
let elemId = elem.closest('table').id; // table id = some...

По сути, через тот же closest() можно искать и родителя, тут в зависимости от ситуации варианты рассматривать надо

3

Есть метод closest, который помогает искать родителя по какому-то селектору.

В случае с вашей таблицей:

const input = document.getElementById('myInput');
const table = input.closest('#some');
if (table) {
  console.log('Parent of input is: ', table);
}
<table id="some">
    <tbody>
        <tr><td><input id="myInput" type="text"></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
    </tbody>
<table>

Полезные ссылки

2

введите сюда описание изображения

Closest не поддерживается IE, так что в дополнение к другим ответам - полифил:

if (!Element.prototype.closest) {

    Element.prototype.closest = function(css) {
        var node = this;

        while (node) {
            if (node.matches(css)) return node;
            else node = node.parentElement;
        }
        return null;
    };
}

0

Если нужен именно n родительский элемент, то можно написать свою функцию:

const nParent = (node, n) => {
  while (node) {
    if (n-- <= 0) return node;
    else node = node.parentElement;
  }
  return null;
}

const x6 = document.getElementById('x6');

console.log(nParent(x6,0));
console.log(nParent(x6,1));
console.log(nParent(x6,2));
console.log(nParent(x6,3));
console.log(nParent(x6,4));
console.log(nParent(x6,5));
console.log(nParent(x6,6));
console.log(nParent(x6,7));
console.log(nParent(x6,8));
<div id="x1">
  <div id="x2">
    <div id="x3">
      <div id="x4">
        <div id="x5">
          <div id="x6"></div>
        </div>
      </div>
    </div>
  </div>
</div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.