简体   繁体   中英

Clicking children of class in pure javascript

Below is sample html , where i am trying to click close button , there are many close buttons, but i want to click close button that is inside class mytop

<div class="mytop">
<a class="mychild" role="button" href="#">Close</a>
</div>

I am trying to get javascript equivalent code for below jquery

$(".mytop").children(".mychild").click();
var topEl = document.querySelector('.mytop');
var closeBtn = topEl.querySelector('a.mychild');
closeBtn.click();

grap class by getElementsByClassName and use addEventListener for event function..

Use window.onload because you can only grap childnode after your document is loaded

window.onload = function(){
var top = document.getElementsByClassName("mytop");
  top[0].children[0].onclick = function(){
        alert(this.className); //mychild
  };  
}

Use document.querySelector(<selector string>)

For your use case, the code would look something like the following:

var closeButton = document.querySelector('.mytop a.mychild');
closeButton.click();

Am am assuming you wanted to simulate a click - not listen for one and fire a function.

var child = document.getElementsByClassName("mytop").childNodes;
 child[0].onclick = function(){
    alert("dsf");
 };

Right i am selecting the first child element only in the above code.

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