1

I've seen many times how to get the DOM path of an element using JQuery, but never how to go in the opposite direction: how do I get the element from the DOM path?

Suppose I have a DOM path like "html/body/div1/div2/div2/div3/div3/em"; I want to highlight the element described by the path, so I need to create a JQuery selector that points to that element, and then I'll be free to use some functions to highlight it.

How do I do that?

At the moment, I tried to construct a function that will split the path in an array, then cycle over it, processing everytime all the children nodes until I find the node I need; as you may understand, it's quite complicated, especially because I may find EVERY html tag, and I can't make a switch case for every tag... I hope there's something quicker and simpler.

In any case, here's what I've done at the moment:

function reconstructNodes(selectorlist)
{
    var range = $('#panelWithHTML').children();
    var array = selectorlist.split("/");
    for (var i = 0; i < array.length; i++) {

        range = range.children();

        switch (array[i]) {
            case 'html':
                for (var j = 0; j < range.length; j++)
                {
                    if (range[j].tagName === 'BODY') {
                        range = range[j];
                    } 
                }
                break;
            case 'body':
                for (var j = 0; j < range.length; j++)
                {

                }
                break;
        }
    }
}

As you can see, I started with the switch, but it's gonna be an eternal code writing.

Any idea?

tenik
  • 250
  • 1
  • 4
  • 20

0 Answers0