faster way to select an element, using javascript

Viewed 180

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>
3 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>

This is a handy trick that I use often. It looks a lot like jQuery, but it isn't.

const $ = document.querySelector.bind(document);
const it = $('container').innerText

or

const $$ = document.querySelectorAll.bind(document);
const it = $$('#container p')[0].getElementsByTagName('strong')[1].innerText

Not exactly jQuery, but somewhat less typing than without - and reuseable throughout the javascript file.

And, of course, mplugian's worthy answer (this answer thread) can also be incorporated into this handy shorthand.

const $ = document.querySelector.bind(document);
const txt = $('#container > p:first-of-type > strong:nth-child(2)').innerText
console.log(txt);
<div id='container'>
   <p>
      <strong></strong>
      <strong> what I would like to get</strong>
   </p>
   <div id='moredivs'>
   </div>
   <div id='moredivs'>
   </div>
</div>

Reference:

https://dev.to/mrahmadawais/use-instead-of-document-queryselector-all-in-javascript-without-jquery-3ef1

<div id='container'>
  <p>
    <strong></strong>
    <strong id='thisText'> what I would like to get</strong>
  </p>
<div id='moredivs1'> //classes are reusable, ids "aren't"
</div>
<div id='moredivs2'>
</div>
</div>

with:

document.querySelector('#thisText').innerText

This is what I use most often

Related