Get values in array from XPATH in Javascript

Viewed 2122

How to get iterated value of an object returned from XPATH request.

I have this HTML template:

<div class="item">
<span class="light">Date</span>
<a class="link" href="">2018</a>
(4pop)
</div>

<div class="item">
<span class="light">From</span>
<span>
<a class="link" href="" title="Bob" itemprop="url"><span itemprop="name">Bob</span></a>,
</span>
<span>
<a class="link" href="" title="Peter" itemprop="url"><span itemprop="name">Peter</span></a>
</span>
</div>

<div class="item">
<span class="light">For</span>
<a class="link" href="">Bak</a>,
<a class="link" href="">Cam</a>,
<a class="link" href="">Oli</a>
</div>

<div class="item">
<span class="light">Nat</span>
<a class="link" href="">Cool</a>
</div>
</div>    

And my Javascript code:

var doc = new DOMParser().parseFromString(HTMLContent,'text/html');
var infos = doc.evaluate('//div[@class="item"]/span[1]', doc, null, XPathResult.ANY_TYPE, null);

var nodes = [];
for(var node = infos.iterateNext(); node; node = infos.iterateNext()) {
    nodes.push(node);
    console.log(node.textContent);

    // Until here, all things works well ! Except the code from here:
    var nodde = node.nextElementSibling.attributes;

    nodde.forEach(function(item){
        console.log(item);
    });
}

My goal is to get the respective value for each categorie, for example:

Date = 2018, (4pop)
From = Bob, Peter
For = Bak, Cam, Oli
Nat = Cool

I tried to iterate: node.nextElementSibling.attributes but without any success !

What i have tried:

var nodde = node.nextElementSibling.attributes;
nodde.forEach(function(item){
    console.log(item);
});

You can check it on the Javascript code, but unfortunatelly This will give null result.

Is there a way to get the expected result please ?

1 Answers

Once you get an item you can iterate through childNodes which include tags and texts.

var items = document.evaluate('//div[@class="item"]', doc, null, XPathResult.ANY_TYPE, null);
while (item = items.iterateNext()) {
    var values = [];
    var nodes = item.childNodes;
    for (var i = 2; i < nodes.length; i++) {
        var value = nodes[i].textContent.trim().replace(',', '');
        if (value.length) values.push(value);
    }
    console.log(item.getElementsByClassName('light')[0].innerText + " = " + values.join(', '));
}

Prints:

Date = 2018, (4pop)
From = Bob, Peter
For = Bak, Cam, Oli
Nat = Cool
Related