document.getElementsByClassName and document.getElementById

document.getElementsByClassName() and document.getElementById(), you should be very familiar with the js methods of these two methods, that is, to obtain DOM elements, what is the difficulty. Today I made a mistake with these two simple methods.

There is a button button on my page, please paste the structure code of the button directly, it is not intuitive, it is best to look at the code directly.

 <button type="button" class="btn" id="btn-commit">提交</button>

The effect I want is to get the button and then bind a click event to the button. Seeing this requirement, how simple it is, I will write the code directly:

 document.getElementsByClassName("btn").onclick = function(){ console.log(333); };

After the code is written, it is found that it does not take effect. I double checked the code, the code is not wrong, and the syntax is not wrong. Finally, I started to check the method of event binding, and there was no problem. I can’t find the problem, this problem has completely stunned me.

Rewrite the code, then get the element by ID and bind the event, the result is a success.

 <button id="btn-focus" class="btn">聚焦</button>
 var btnFocus = document.getElementById("btn-focus"); btnFocus.onclick = function(){ console.log(12); };

I changed the way to get elements from id to class, and the effect is not working again. Now I have probably found the cause of the problem, and printed them separately:

document.getElementsByClassName(“btn”) and document.getElementById(“btn-commit”);

 console.log(document.getElementsByClassName("btn")); console.log(document.getElementById("btn-commit"));

Execution result, paste a picture:

As you can see from here, the element obtained by getElementsByClassName() is a collection of elements, and the element obtained by getElementById() is an element. No wonder I did not respond to the event bound by getElementsByClassName(), this is the reason.

Originally, these two methods are quite simple. Due to negligence, it cannot be said to be negligent, but I didn’t pay attention to this detail. Previously, the operation of the DOM heavily relied on jQuery, which resulted in some basic skills being left behind. became bitter fruit. Fortunately, I found this problem, this little lesson, I hope it can give me a long memory. Then there is the serious dependence on the tool library that cannot be separated from the basic skills.

The post document.getElementsByClassName and document.getElementById first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/9090
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment