Parent content in javascript

Writing a .parents() function using Vanilla JS

Moving away from the super useful and powerful Jquery in order to use more modern frameworks (such as React, Vue and Ember JS), the thing i miss the most about jquery was its super simple DOM manipulation that we don’t have with Vanilla JS. My top favorite built in functions were the .parents() function and the .on() event handlers (the $ elm saved so many charactersof code!). These 2 functions single handedly reduced Vanilla JS code by a factor of 10x at least. The .on() function in jquery let us bind an event handler such as click to any number of elements as easy as:

$('p').on("click", function()  //execute anything when any of the p tags on the page are clicked > 

That was super cool and useful. Now with Vanila JS we know we must loop through the collection of p tags and bind click events to each item in that collection (as they are treated as an array).
The code is much more complex:

const p = document.querySelectorAll('p') for(item of p)  p.onclick = () =>  //ES6 //execute actions when p tags are clicked > > 

As we can see its doable but adds easily 3-4 lines of extra code (even using ES6) But for the magical .parents() function, Javascript does not even provide us a long or short way to achieve what jquery did. So let’s see what we need to design in order to simulate the .parents() behaviour. In the end it’ll add almost 20 lines of extra code as opposed to just writing .parents() but we’ll have a readily available function that we can reuse whenever we want! Its gonna be a little long but stick around I promise you won’t regret it.

function getParents(el, parentSelector)  if (parentSelector === undefined)  parentSelector = document; > var parents = []; var p = el.parentNode; while (p !== parentSelector)  var o = p; parents.push(o); p = o.parentNode; > parents.push(parentSelector); return parents; > 

Explainging the Code

Let’s understand this code. The first line initiates the function and passes two parameters, the actual element which we are at and an optional parent selector to stop our parent search at. The second line says if we dont provide a parent selector then set the parent selector as the root-most element, which is the document itself (above the html tag). Then we create a parent array and stuff all of the parent elements of our element. We then have a while loop that dictates that while the current parent node is not our provided parent selector (or document) then assign that node to a variable o and push o into the parents array.
So every iteration where that parent node is not the provided parent selector, we add that node to an array. Eventually our provided parent selector will be the current parent node as it goes up and compares to every parent node all the way up the DOM.
Once there is a match, the while loop will stop, the array will finally push our provided parent selector and thus the highest parent node will be at the end of the array. Finally we return the array parents and we are done. Now how do we actually make use of our custom built function to use like .parents() in jquery? Simple. We call the function on the element we want and pass as arguments our element and a max parent selector like so:

//parentDiv is our max parent selector const button = document.querySelector('button') const parentDiv = document.querySelector('.parentdiv') //here we call our getParents function const parents = getParents(button, parentDiv) //and here the magic happens, since our parent node is always the last one parents[parents.length-1] 

Since our parent selector is always the last one we can refer to it simply by using our parents array and retrieving the last element in the array by doing parents.length-1 (will get the last element in the array). We can then do

parents[parents.length-1].querySelector('p').innerHTML //finds a p tag's inner html contents inside our parents element, just like in jquery 

Comparing Jquery to Vanilla JS

//jquery var mytxt = $('button').parents('.parent1').find('p').html() //will get us the html content of a p element inside the parent div of our button - super useful DOM manipulation //Vanilla JS const parents = getParents(button, parent1)//assuming button and parent1 are already assigned const mytxt = parents[parents.length-1].querySelector('p').innerHTML 

Final Thoughts

Sure the Vanilla JS solution required quite some extensive code but ultimately its not that bad and well worth to use if we reuse the function across our app. Thanks for taking interest in my post and reading up to the end. I hope you will find this useful and that it helps you in your future coding projects!

Источник

DOM позволяет нам делать что угодно с элементами и их содержимым, но для начала нужно получить соответствующий DOM-объект.

Все операции с DOM начинаются с объекта document . Это главная «точка входа» в DOM. Из него мы можем получить доступ к любому узлу.

Так выглядят основные ссылки, по которым можно переходить между узлами DOM:

Поговорим об этом подробнее.

Сверху: documentElement и body

Самые верхние элементы дерева доступны как свойства объекта document :

= document.documentElement Самый верхний узел документа: document.documentElement . В DOM он соответствует тегу . = document.body Другой часто используемый DOM-узел – узел тега : document.body . = document.head Тег доступен как document.head .

Нельзя получить доступ к элементу, которого ещё не существует в момент выполнения скрипта.

В частности, если скрипт находится в , document.body в нём недоступен, потому что браузер его ещё не прочитал.

Поэтому, в примере ниже первый alert выведет null :

        

В DOM значение null значит «не существует» или «нет такого узла».

Дети: childNodes, firstChild, lastChild

Здесь и далее мы будем использовать два принципиально разных термина:

  • Дочерние узлы (или дети) – элементы, которые являются непосредственными детьми узла. Другими словами, элементы, которые лежат непосредственно внутри данного. Например, и являются детьми элемента .
  • Потомки – все элементы, которые лежат внутри данного, включая детей, их детей и т.д.

    (и несколько пустых текстовых узлов):

    и вложенные в них:
    (ребёнок

      ) и (ребёнок
      ) – в общем, все элементы поддерева.

    Коллекция childNodes содержит список всех детей, включая текстовые узлы.

    Пример ниже последовательно выведет детей document.body :

    Обратим внимание на маленькую деталь. Если запустить пример выше, то последним будет выведен элемент . На самом деле, в документе есть ещё «какой-то HTML-код», но на момент выполнения скрипта браузер ещё до него не дошёл, поэтому скрипт не видит его.

    Свойства firstChild и lastChild обеспечивают быстрый доступ к первому и последнему дочернему элементу.

    Они, по сути, являются всего лишь сокращениями. Если у тега есть дочерние узлы, условие ниже всегда верно:

    elem.childNodes[0] === elem.firstChild elem.childNodes[elem.childNodes.length - 1] === elem.lastChild

    Для проверки наличия дочерних узлов существует также специальная функция elem.hasChildNodes() .

    DOM-коллекции

    Как мы уже видели, childNodes похож на массив. На самом деле это не массив, а коллекция – особый перебираемый объект-псевдомассив.

    И есть два важных следствия из этого:

    for (let node of document.body.childNodes) < alert(node); // покажет все узлы из коллекции >

    Это работает, потому что коллекция является перебираемым объектом (есть требуемый для этого метод Symbol.iterator ).

    alert(document.body.childNodes.filter); // undefined (у коллекции нет метода filter!)

    Первый пункт – это хорошо для нас. Второй – бывает неудобен, но можно пережить. Если нам хочется использовать именно методы массива, то мы можем создать настоящий массив из коллекции, используя Array.from :

    alert( Array.from(document.body.childNodes).filter ); // сделали массив

    DOM-коллекции, и даже более – все навигационные свойства, перечисленные в этой главе, доступны только для чтения.

    Мы не можем заменить один дочерний узел на другой, просто написав childNodes[i] = . .

    Для изменения DOM требуются другие методы. Мы увидим их в следующей главе.

    Почти все DOM-коллекции, за небольшим исключением, живые. Другими словами, они отражают текущее состояние DOM.

    Если мы сохраним ссылку на elem.childNodes и добавим/удалим узлы в DOM, то они появятся в сохранённой коллекции автоматически.

    Коллекции перебираются циклом for..of . Некоторые начинающие разработчики пытаются использовать для этого цикл for..in .

    Не делайте так. Цикл for..in перебирает все перечисляемые свойства. А у коллекций есть некоторые «лишние», редко используемые свойства, которые обычно нам не нужны:

       

    Соседи и родитель

    Соседи – это узлы, у которых один и тот же родитель.

    • говорят, что – «следующий» или «правый» сосед
    • также можно сказать, что «предыдущий» или «левый» сосед .

    Следующий узел того же родителя (следующий сосед) – в свойстве nextSibling , а предыдущий – в previousSibling .

    Родитель доступен через parentNode .

    // родителем является alert( document.body.parentNode === document.documentElement ); // выведет true // после идёт alert( document.head.nextSibling ); // HTMLBodyElement // перед находится alert( document.body.previousSibling ); // HTMLHeadElement

    Навигационные свойства, описанные выше, относятся ко всем узлам в документе. В частности, в childNodes находятся и текстовые узлы и узлы-элементы и узлы-комментарии, если они есть.

    Но для большинства задач текстовые узлы и узлы-комментарии нам не нужны. Мы хотим манипулировать узлами-элементами, которые представляют собой теги и формируют структуру страницы.

    Поэтому давайте рассмотрим дополнительный набор ссылок, которые учитывают только узлы-элементы:

    Эти ссылки похожи на те, что раньше, только в ряде мест стоит слово Element :

    • children – коллекция детей, которые являются элементами.
    • firstElementChild , lastElementChild – первый и последний дочерний элемент.
    • previousElementSibling , nextElementSibling – соседи-элементы.
    • parentElement – родитель-элемент.

    Свойство parentElement возвращает родитель-элемент, а parentNode возвращает «любого родителя». Обычно эти свойства одинаковы: они оба получают родителя.

    За исключением document.documentElement :

    alert( document.documentElement.parentNode ); // выведет document alert( document.documentElement.parentElement ); // выведет null

    Причина в том, что родителем корневого узла document.documentElement ( ) является document . Но document – это не узел-элемент, так что parentNode вернёт его, а parentElement нет.

    Эта деталь может быть полезна, если мы хотим пройти вверх по цепочке родителей от произвольного элемента elem к , но не до document :

    while(elem = elem.parentElement) < // идти наверх до alert( elem ); >

    Изменим один из примеров выше: заменим childNodes на children . Теперь цикл выводит только элементы:

    Источник

    HTML DOM parentElement Property

    Click on an element () to hide its parent element ():

    Description

    The parentElement property returns the parent element of the specified element.

    The difference between parentElement and parentNode, is that parentElement returns null if the parent node is not an element node:

    document.body.parentNode; // Returns the element
    document.body.parentElement; // Returns the element

    document.documentElement.parentNode; // Returns the Document node
    document.documentElement.parentElement; // Returns null ( does not have a parent ELEMENT node)

    In most cases, it does not matter which property you use, however, parentNode is probably the most popular.

    This property is read-only.

    HTML Nodes vs Elements

    In the HTML DOM (Document Object Model), an HTML document is a collection of nodes with (or without) child nodes.

    Nodes are element nodes, text nodes, and comment nodes.

    Whitespace between elements are also text nodes.

    Elements are only element nodes.

    childNodes vs children

    childNodes returns child nodes (element nodes, text nodes, and comment nodes).

    children returns child elements (not text and comment nodes).

    Siblings vs Element Siblings

    Siblings are «brothers» and «sisters».

    Siblings are nodes with the same parent (in the same childNodes list).

    Element Siblings are elements with the same parent (in the same children list).

    Syntax

    Technical Details

    Return Value: An Element object, representing the parent element node of a node, or null if the node has no parent

    Browser Support

    element.parentElement is a DOM Level 3 (2004) feature.

    It is fully supported in all modern browsers:

    Chrome Edge Firefox Safari Opera IE
    Yes Yes Yes Yes Yes 11

    Источник

    Читайте также:  Centering div in body html
Оцените статью