Node.parentElement
Свойство Node.parentElement только для чтения, возвращает родителя узла DOM Element , или null если узел не имеет родителя, или его родитель не DOM Element .
Синтаксис
parentElement это родительский элемент текущего узла. Это всегда объект DOM Element , или null .
Пример
Совместимость с браузерами
BCD tables only load in the browser
В некоторых браузерах, свойство parentElement определено только для узлов, которые сами Element . В частности, не определено для текстовых узлов.
How to get a parent element with vanilla JS
Today, we’re going to look at two ways to get a parent element with vanilla JS.
The parentNode property
Every element in the DOM has a parentNode property on it. This returns the parent of the element.
Let’s look at a list of items.
Using the parentNode property, we can get the parent element ( #list ) of our #c list items.
Finding the first parent that matches a selector with the closest() method
Let’s say you had a nested list, and you wanted to find the first parent element with a class of .top .
You can call the closest() method on the element you want to find the matching parent for, and pass in the selector as an argument.
The closest() method will also check the element it’s called on, so if the #c2 element had the .top class on it, that would be the matching result.
You can start with the first parent element by combining the parentNode property and closest() method together.
Browser compatibility
The parentNode property works in all modern browsers, and back to at least IE6.
The closest() method works in all modern browsers, but has no IE support. You can push support back to IE9 with a polyfill.
Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. Join over 14k others.
Made with ❤️ in Massachusetts. Unless otherwise noted, all code is free to use under the MIT License. I also very irregularly share non-coding thoughts.
Навигация по DOM-элементам
DOM позволяет нам делать что угодно с элементами и их содержимым, но для начала нужно получить соответствующий DOM-объект.
Все операции с DOM начинаются с объекта document . Это главная «точка входа» в DOM. Из него мы можем получить доступ к любому узлу.
Так выглядят основные ссылки, по которым можно переходить между узлами DOM:
Поговорим об этом подробнее.
Сверху: documentElement и body
Самые верхние элементы дерева доступны как свойства объекта document :
<html> = document.documentElement Самый верхний узел документа: document.documentElement . В DOM он соответствует тегу <html> . <body> = document.body Другой часто используемый DOM-узел – узел тега <body> : document.body . <head> = document.head Тег <head> доступен как document.head .
Нельзя получить доступ к элементу, которого ещё не существует в момент выполнения скрипта.
Как найти родителя родителя родителя в JavaScript?
Как найти родителя родителя родительского элемента? Есть блок (см.картинку), в нем есть кнопка ‘.product__shopcard-btn’ мне нужно найти родителя родителя его родительского элемента т.е. ‘.product’ (надеюсь выразился понятно). Способ element.parentNode.parentNode.parentNode работает, но бред же? Интересует чистый js без jquery.