简体   繁体   中英

Javascript DOM: What is the recommended way to search a child element in HTMLDivElements how it does document.getElementById?

When i search for a element by example by Id, I use the well know method getElementById like this:

HTML

<div id="my-first-div">
    <div class="anotherDiv">
        <button id="main-btn"> </button>
    </div>
</div>

Javascript

const mainDiv = document.getElementById("my-first-div");
const mainButton = mainDiv.querySelector("#main-btn");
//const mainButton = mainDiv.getElementById("main-btn"); //this doesn't work

So, the only way for find a child inside of a div is using querySelector method that in this basic example works fine, but for huge HTML markup it's more slow compared with the document.getElementById . See https://jsperf.com/getelementbyid-vs-queryselector/11

My question is:

Exists a better way for find child elements by id (or class, or tagName) without use querySelector for HTMLDivElement?

EDIT

I just noticed that you were already aware of document.querySelector - use it until it becomes too slow for you. Just because it's slower than document.getElementById doesn't mean it's not still ridiculously fast.

Like one of the commentors pointed out, don't optimize prematurely.

As an answer to you question, no the browser exposes no other usable API that is faster than these APIs to get DOM elements and I imagine that all of the getElement(s)By methods probably internally route to a querySelector method with a flag to return the first or all of the matched nodes.

ORIGINAL ANSWER

document also contains the querySelector method :

const mainDiv = document.getElementById("my-first-div");
const mainButton = mainDiv.querySelector("#main-btn");

is the same as:

const mainButton = document.querySelector('#my-first-div #main-btn');

That being said, if main-btn is an id , then it's unique so you can just do:

const mainButton = document.getElementById('main-btn');

There are other JavaScript methods that are "equivalent" to a single facet of querySelector() and theoretically should be faster since these methods do one thing only.

Normally these methods will collect all of whatever they are designed to collect and return a HTMLCollection (an array-like object that is "live", meaning that if anything is added or removed, or changed in some way, it will automatically comply to said changes.) Notice the bracket notation [0] . This will return the first element of a document (or element) just like .querySelector() .

Also added some HTMLElement Interfaces for <table> and <form> .

Demo

 var gTagName = document.getElementsByTagName('ASIDE')[0]; var qTagName = document.querySelector('ASIDE'); var gName = document.getElementsByName('TEXT')[0]; var qName = document.querySelector('[name=TEXT]'); var gClass = document.getElementsByClassName('h')[0]; var qClass = document.querySelector('.h'); var qAttribute = document.querySelector('[href]'); qTagName.style.border = '3px solid blue'; qName.style.backgroundColor = 'cyan'; qClass.style.backgroundColor = 'darkblue'; qAttribute.style.color = 'midnightblue'; gTagName.style.backgroundColor = 'tomato'; gName.style.border = '3px solid red'; gClass.style.backgroundColor = 'orange'; var cForm = document.forms[0]; var cFields = cForm.elements; for (var F of cFields) { F.style.border = '3px dashed brown'; } cFields[1].value = 'HTMLFormControlsCollection'; cFields[1].style.transform = 'scale(2,2)'; var cTable = document.querySelector('table'); var cRows = cTable.rows; var cCells = cRows[0].cells cCells[2].textContent = 'This cell\\'s just got content'; cCells[2].style.color = 'red'; 
 div { border: 1px dashed red } td { border: 1px solid blue } input { display: inline-block; } 
 <div class='a'>&lt;DIV&gt;ISION a <div class='b'>&lt;DIV&gt;ISION b <table> <caption>&lt;TABLE&gt; get by HTMLTableCollection</caption> <tr> <td>TABLE DATA</td> <td>TABLE DATA</td> <td>TABLE DATA</td> <td>TABLE DATA</td> </tr> </table> <div class='c'>&lt;DIV&gt;ISION c <input name='TEXT' value='&lt;INPUT&gt; get by NAME'> <div class='d'>&lt;DIV&gt;ISION d <div class='e'>&lt;DIV&gt;ISION e <a href='#/'>&lt;A&gt;NCHOR get by [ATTRIBUTE]</a> <div class='f'>&lt;DIV&gt;ISION f <form><input value='&lt;INPUT&gt;'> <input value='&lt;INPUT&gt;'> <input value='&lt;INPUT&gt;'> </form> <div class='g'>&lt;DIV&gt;ISION g <aside>&lt;ASIDE&gt; get by TAGNAME</aside> <div class='h'>&lt;DIV&gt;ISION h get by .CLASS <div class='i'>&lt;DIV&gt;ISION i <div class='j'>&lt;DIV&gt;ISION j </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> 

try

document.getElementsByClassName('.class')
document.getElementsByTagName('div')

though getElementById is the quickest of the 3

the more specific you are with your classes the easier they will be to find

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM