DOM:如何检测新的子元素?

时间:2022-10-27 11:42:05

I want to detect the insertion of a new div element only as a direct child of the parent div.

我希望仅作为父div的直接子元素检测新div元素的插入。

Example:

例子:

<div id="parent">
    <div id="child1"></div>
    <div id="child2"></div>
    <div id="newChild">I want this element to be detected</div>
</div>

The DOMNodeInserted() event is not a solution for me because it is triggered on every element insertion, not just children.

domnodeinsert()事件对我来说不是一个解决方案,因为它是在每个元素插入时触发的,而不仅仅是子元素。

Like:

如:

<div id="parent">
    <div id="child1">
        <span>I don't want this new element to be detected</span>
    </div>
    <div id="child2"></div>
    <div id="child3"></div>
</div>

3 个解决方案

#1


3  

Assume your event handler looks like this:

假设事件处理程序如下:

function(evt) {
    // whatever
}

Inside the handler, evt.relatedNode is the element into which the insertion is being performed. You can switch on it and decide to ignore or process the event.

处理程序内部,evt。relatedNode是执行插入的元素。您可以打开它并决定忽略或处理该事件。

See it in action.

看它的实际应用。

#2


7  

Use DOMNodeInserted on the parent and check the event.target.parentNode of the added element. If its id is parent, then the element is a direct descendant.

在父节点上使用domnodeinsert,并检查事件.target。添加元素的parentNode。如果它的id是父元素,那么元素就是直接的后代元素。

Demo: http://jsfiddle.net/ThinkingStiff/f2w7V/

演示:http://jsfiddle.net/ThinkingStiff/f2w7V/

document.getElementById( 'parent' ).addEventListener( 'DOMNodeInserted', function ( event ) {

    if( event.target.parentNode.id == 'parent' ) {
        //direct descendant        
    };

}, false );

#3


0  

Why don't you use DOMNodeInserted, but add a check / if-statement in the event handler so the real logic only runs when you want it to?

为什么不使用domnodeplugged,而是在事件处理程序中添加check / if语句,以便真正的逻辑只在您希望它运行的时候运行?

#1


3  

Assume your event handler looks like this:

假设事件处理程序如下:

function(evt) {
    // whatever
}

Inside the handler, evt.relatedNode is the element into which the insertion is being performed. You can switch on it and decide to ignore or process the event.

处理程序内部,evt。relatedNode是执行插入的元素。您可以打开它并决定忽略或处理该事件。

See it in action.

看它的实际应用。

#2


7  

Use DOMNodeInserted on the parent and check the event.target.parentNode of the added element. If its id is parent, then the element is a direct descendant.

在父节点上使用domnodeinsert,并检查事件.target。添加元素的parentNode。如果它的id是父元素,那么元素就是直接的后代元素。

Demo: http://jsfiddle.net/ThinkingStiff/f2w7V/

演示:http://jsfiddle.net/ThinkingStiff/f2w7V/

document.getElementById( 'parent' ).addEventListener( 'DOMNodeInserted', function ( event ) {

    if( event.target.parentNode.id == 'parent' ) {
        //direct descendant        
    };

}, false );

#3


0  

Why don't you use DOMNodeInserted, but add a check / if-statement in the event handler so the real logic only runs when you want it to?

为什么不使用domnodeplugged,而是在事件处理程序中添加check / if语句,以便真正的逻辑只在您希望它运行的时候运行?