简体   繁体   中英

DOM help, parents of parents, children of children

I am using Drupal's Webform module which writes all the ids and classes automatically, so I can't add an Id to the place I want to add it. And Drupal doesn't put one in for me. Grrr.

I have no problem when I use my code with just a simple getElementById('myid'), but the element I need is a blank, no id, no class "a" that's inside a "legend" (which has a class but no id) that's inside a fieldset with an id.

I tried this code and several variations but it didn't work:

document.getElementById('webform-created-id-here').getElementsByTagName('legend').getElementsByTagName('a');

I feel like I'm not understanding how to properly access that part of the DOM. Can anyone offer help or suggestions?

Thank you!

getElementsByTagName return a nodelist with the elements found, so you must select the index of the element

Example for the first element

var test = document.getElementById('webform-created-id-here').getElementsByTagName('legend')[0].getElementsByTagName('a')[0];

DEMO VIEW

Recurse through the DOM yourself. References to the children of any element are stored in the childNodes attribute which exist for every node.

function recurseDOM (el,test) {
    if (test(el)) {
        return el;
    }
    else {
        var children = el.childNodes;
        var result;
        for (var i=0; i<children.length; i+) {
            result = recurseDOM(children[i],test);
            if (result) {
                return result;
            }
        }
    }
    return null;
}

This is only one possible implementation that I wrote in the 2 minutes it took me to type out this answer. So it can probably use some improvements. But you get the idea.

Use it like this:

recurseDOM(document.body,function(el){
    if (el == something_something) { return 1}
    return 0
});

You can write a similar function to test parents:

function testParents (el, test) {
    var parent = el.parentNode;

    if (test(parent)) {
        return 1;
    }
    else {
        if (parent != document.body) {
            return testParents(parent,test);
        }
    }
    return 0;
}

So you can write something like:

recurseDOM(document.body,function(el){
    if (el.tagName == 'a' && testParents(el,function(p){
        if (p.tagName == 'legend' && testParents(p,function(pp){
            if (pp.id == 'webform-created-id-here') {
                return 1;
            }
            return 0;
        })) {
            return 1;
        }
        return 0;
    })) {
        return 1;
    }
    return 0;
});

Alternatively, you can start the recursion form the getElementById instead of document.body .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM