0

I have button with onclick :

 <button   class="tablinks" onclick="openDiv(event, 'default')">{'TEXT_DEFAULT_SETTINGS'|tr}</button>

openDiv function:

function openDiv(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;
  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

How can I trigger this onclick?

2
  • document.querySelector(validSelctor).click() Commented May 30, 2017 at 15:09
  • Its will work if you have element with id that passed you cityName Commented May 30, 2017 at 15:42

2 Answers 2

2

Try:

document.getElementsByClassName("tablinks")[0].click()
Sign up to request clarification or add additional context in comments.

Comments

1

Your code working fine unless you dont have element with default as id. Else your code ll break & give error as Uncaught TypeError: Cannot read property 'style' of null for this statement document.getElementById(cityName).style.display = "block";

See the below working example of your code:

function openDiv(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;
  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
#default {
display:none
}
 <button   class="tablinks" onclick="openDiv(event, 'default')">{'TEXT_DEFAULT_SETTINGS'|tr}</button>

<div id="default">
This is a default div
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.