personalt
personalt

Reputation: 850

Xpath - select element with only closing tag

I am new to xpath and have been stuck on this for way too long. Is it possible to get to the upc value of 0305064523219 from the example below?

I was trying //div[@class='prdct3']/strong[4] but of course that only includes 'UPC:' in between the strong tags. I need to go out to the <br /> tag. is there a way to have xpath get the element after an element?

<div class="prdct3">
<p><strong>Description:</strong></p>

<p><a href="/catalog/?JOJ4026UP=jojoblister-card-2-
colors-asstd">Digital Watch on Blister Card 2 Colors Asstd.</a></p>
<strong>Item Size:</strong> 6.75" x 3.5" x .75"<br />
<strong>Case:</strong> 144 <strong>Inner:</strong> 24<br />
<strong>UPC:</strong> 0305064523219<br />
<strong>WT:</strong> 10 <strong>CF:</strong> 1.82<br />
<strong>Sub-Category:</strong> AC06<br />
<strong>Origin:</strong> China<br /><div class="floatRight"><a 
class='iframe' href="/_forms/?JOJ4032P"><img 
 src="/_images/btn_questions.jpg" alt="" /></a></div>
</div>

Upvotes: 1

Views: 1058

Answers (1)

melpomene
melpomene

Reputation: 85867

The following seems to work:

function xpath(selector, root) {
    return document.evaluate(selector, root || document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

var node = xpath('//div[@class="prdct3"]/strong[text()="UPC:"]/following-sibling::text()[1]');
console.log(node.textContent);
<div class="prdct3">
<p><strong>Description:</strong></p>

<p><a href="/catalog/?JOJ4026UP=jojoblister-card-2-
colors-asstd">Digital Watch on Blister Card 2 Colors Asstd.</a></p>
<strong>Item Size:</strong> 6.75" x 3.5" x .75"<br />
<strong>Case:</strong> 144 <strong>Inner:</strong> 24<br />
<strong>UPC:</strong> 0305064523219<br />
<strong>WT:</strong> 10 <strong>CF:</strong> 1.82<br />
<strong>Sub-Category:</strong> AC06<br />
<strong>Origin:</strong> China<br /><div class="floatRight"><a 
class='iframe' href="/_forms/?JOJ4032P"><img 
 src="/_images/btn_questions.jpg" alt="" /></a></div>
</div>

We find the strong tag whose text is UPC:, then take the first following sibling text node.

following-sibling:: is an axis.

Upvotes: 2

Related Questions