Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could simply use querySelector

const text = document.querySelector('p > strong').innerText
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!