Skip to content Skip to sidebar Skip to footer

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]

Solution 1:

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>

Solution 2:

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


Solution 3:

<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


Post a Comment for "Faster Way To Select An Element, Using Javascript"