Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

faster way to select an element, using javascript

I would like to know if there's a faster way to select this:

document.getElementById('container')
        .getElementsByTagName('p')[0]
        .getElementsByTagName('strong')[1]
        .innerText

The structure is:

<div id='container'>
   <p>
      <strong></strong>
      <strong> what I would like to get</strong>
   </p>
   <div id='moredivs'>
   </div>
   <div id='moredivs'>
   </div>
</div>
like image 428
Uniextra Avatar asked Jan 25 '23 15:01

Uniextra


1 Answers

Faster, no - more elegantly, yes:

FIRST you need valid HTML:

console.log(
  document.querySelector("#container > p > strong:last-child").textContent
);
<div id='container'>
  <p>
    <strong></strong>
    <strong>Text I'd like to get</strong>
  </p>
</div>
like image 184
mplungjan Avatar answered Jan 30 '23 11:01

mplungjan