-1

I am trying to access a button directly (I do not think there is a way) in my JavaScript code which is placed in a long nested div containers as shown below. Is there an easy way that my button element can be found with a name and I do not have to call each div to go to my button?

<iframe allowfullscreen="true" title="myFile" style="width: 100%; height: 100%; border: 0px; display: block;">
<div class="1">
  <div class="2"> 
    <div class="3"> 
     <div class="4">
      <div class="5">
       <div class="6"> 
         <div class="7"> 
           <div class="8">
           <button  class="myButton" type="button"> </button>
                </div>
              </div>
            </div>
           </div> 
          </div>
        </div>
    </div>
</div>
</iframe>

JS

function AccessButton() {  

    var bt = document.getElementsByClassName("myButton");
}  

AccessButton();

EDIT: I am sorry I forgot an extremely important thing. The whole code is present inside an iframe div.

Vika
  • 419
  • 1
  • 13
  • 2
    The only problem is that you use `.getElementById()` although the button has no id. Either make the class an id or use `.getElementsByClassName()` or `.querySelector()` – Andreas Jan 18 '22 at 10:20
  • Sorry yes I did not see that. So I should be doing ```document.getElementsByClassName("myButton")```? – Vika Jan 18 '22 at 10:23
  • If there's only one element with that class then use `.querySelector()` and skip the collection part – Andreas Jan 18 '22 at 10:24
  • Does your page only have one of those buttons? – connexo Jan 18 '22 at 10:25
  • Sorry guys I updated my question. I forgot to add iframe tag. – Vika Jan 18 '22 at 10:31

1 Answers1

2

You can use a querySelector here, it will find the first element in the document that matches the CSS selector passed to it:

function AccessButton() {
  document.querySelector(".a1 .myButton").click();
}

AccessButton();
<div class="a1">
  <div class="a2">
    <div class="a3">
      <div class="a4">
        <div class="a5">
          <div class="a6">
            <div class="a7">
              <div class="a.a1 8">
                <button class="myButton" type="button" onclick="console.log('clicked')">MyButton</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Please note that CSS classes must not start with a number.

connexo
  • 53,704
  • 14
  • 91
  • 128