如何访问第n个父节点

时间:2018-10-05 16:48:01

标签: javascript reactjs

我尝试获取子元素的父div的高度。enter image description here

我有一个Parent的div,其class =“ Parent”也有n个子元素,例如<div data-elementid="el_ryz-E9a349" class="row">

Parent有一个修复问题height: 220px,如果不对此孩子执行<div data-elementid="el_ryz-E9a349" class="row">,我需要知道子元素(n)scrollIntoView()是否以父级高度出现。

重要的是我无法删除这两个元素,空的div<div class="container"因为会影响我的设计。

...
const scrollToBottom = () => {
    const elementNode = document.querySelector(`[data-elementid='${action.payload.id}']`);
    const parentElementNode = elementNode.parentNode;
    const elementsHeight = parentElementNode.offsetHeight;
    const menuContainer = parentElementNode.parentNode.offsetHeight;

    if (elementsHeight > menuContainer) {
      elementNode.scrollIntoView({
        behavior: 'smooth',
        block: 'end',
      });
    }

 };
setTimeout(scrollToBottom, 200);
...

很明显,如果我有n个子元素,则使elementNode.parentNode.parentNode.parentNode访问父节点以获得height属性是多余的。

2 个答案:

答案 0 :(得分:3)

使用此功能可以在元素父级中查找父级名称:

const getParent = (element, cls) => {
    if (element && element.parentElement) {
        const parentClassName = element.parentElement.className;
        if (element.parentElement && parentClassName && parentClassName.match(new RegExp(cls, 'g'))) {
            return element.parentElement; // Found it
        }
        getParent(element.parentElement, cls);
    } else {
        return false; // No parent with such a className
    }
}

const scrollToBottom = () => {
    const elementNode = document.querySelector(`[data-elementid='${action.payload.id}']`);
    const parentElementNode = getParent(elementNode, 'parent'); // second arg is the parent classname you looking for.

    if (parentElementNode) {
        const elementsHeight = parentElementNode.offsetHeight;
        const menuContainer = parentElementNode.parentNode.offsetHeight;

        if (elementsHeight > menuContainer) {
            elementNode.scrollIntoView({
                behavior: 'smooth',
                block: 'end',
            });
        }
    }

    console.log('no parent found!')

};

setTimeout(scrollToBottom, 200);

选择数据属性:

const getParentWithAttr = (element, attr) => {
    if (element && element.parentElement) {
        const parentElement = element.parentElement;
        if (parentElement && parentElement.getAttribute('data-attr') === attr) {
            return parentElement; // Found it
        }
        getParent(parentElement, attr);
    } else {
        return false; // No parent with such a className
    }
}

用例应如下:

<div id="..." class="..." data-attr="parent">// parrent
    ... // chilren
</div>


getParentWithAttr(document.querySelector('.element'), 'parent');

答案 1 :(得分:0)

由于问题的标记为React.js,因此我将改为参考ReactJS how to scroll to an element。这使用了React refs,并使您的代码更加简单。话虽如此,看来问题实际上是在静态HTML上使用纯JavaScript。

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class SampleComponent extends Component {
  scrollToDomRef = () => {
    const myDomNode = ReactDOM.findDOMNode(this.myRef.current)
    myDomNode.scrollIntoView()
  };

  render() {
    return <> // '<></>' is a React 16.3.0+ feature, use <div> if previous
      <button onClick={this.scrollToDomRef}>Click me</div>
      <div ref={ re => { this.myRef = re } }></div>
    </>
  }
}