Javascript traverse towards a p element with a text content and get the value

130 Views Asked by At

I want to get the value of a strong tag with a preceding text inside a p paragraph using plain javascript. Problem is there not even an id or class element for this record, so I am at lost on how to traverse. I have the following html to traverse:

<div class="panel-body">

<p>Short Title: <strong>Strengthening Compliance With Occupational Safety And Health Standards And Providing Penalties For Violations Thereof</strong>
...OMITTED for BREVITY..
<br>
Date Read: 
<strong>2016-07-26</strong>
... 
More p elements same the same pattern as above:
A Header (That I'm interested in to be able to identify what the text is about: <strong>The Text I am interested in</strong> 
...

</div>

I am trying out evaluate, but it seem I can not get what I need:

var text = document.evaluate("//p[contains(., 'Short Title:')]/firstElementChild", document, null, XPathResult.ANY_TYPE, null );
console.log(text);

UPDATE: It seems I am able to traverse my document with the following code below:

var text = document.evaluate("//p[contains(., 'Short Title:')]/childNodes", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null );
if (text.singleNodeValue !== null) {
                    var Details = text.singleNodeValue.textContent;
                }
console.log(Details);

But the problem is that I am also getting all the other text Content inside the div, like so:

Short Title: Strengthening Compliance With Occupational Safety And Health Standards And Providing Penalties For Violations ThereofDate Read: 2016-07-26

UPDATE 2: Apparently, the html document I am trying to traverse inside the p element has more headings that are only separated by breaks "br" tag like so:

<p>Short Title: <strong>The Short Title</strong>
<br>
<strong>Principal Author/s:</strong>
Name of a lot of authors.
<br>
Date Read: 
<strong>2016-07-26</strong>

That could be the reason that my first javascript code is throwing all textcontent of the p element.

1

There are 1 best solutions below

1
ejose19 On

You could simply use querySelector

const text = document.querySelector('p > strong').innerText