简体   繁体   中英

Javascript Function to Click Element that is Defined with Multiple Classes

I am trying to click a button but the only thing that defines it is multiple classes. The element I want to click is

<div class="U26fgb XHsn7e obPDgb M9Bg4d">This is a button </div>

How would I go about clicking it using Javascript ?

As long as it is the only <div> element with that class combination, you'd use .querySelector() , which accepts any valid CSS selector as an argument so you can select elements in JavaScript the same way you would in CSS:

 // Scan the document for the <div> that has the required classes let theDiv = document.querySelector("div.U26fgb.XHsn7e.obPDgb.M9Bg4d"); // Set up a click event handling function theDiv.addEventListener("click", function(){ console.log("you clicked me"); }); // Trigger the click event of the <div> theDiv.click();
 <div class="U26fgb XHsn7e obPDgb M9Bg4d">Click Me</div>

FYI: You should get out of the habit of putting spaces on the insides of the < and > delimiters in HTML. Use this:

<div class="U26fgb XHsn7e obPDgb M9Bg4d">Click Me</div>

Not this:

< div class="U26fgb XHsn7e obPDgb M9Bg4d" >Click Me< /div >

very simple with jQuery:

$(".U26fgb.XHsn7e.obPDgb.M9Bg4d").click(function(){
  console.log("clicked!");
}); 
const div = document.querySelector('div .M9Bg4d');
div.addEventListener("click", ()=> {
 // here put what you wanna do after clicking the div.

});

onclick attribute works well inside almost all the html tags and here is the simple solution to click on the div and get a result. All the Best!

 function clickDiv(){ console.log("Div is Clicked"); }
 <div class="U26fgb XHsn7e obPDgb M9Bg4d" onclick="clickDiv()">This is a button </div>

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