Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to target a button from a group of buttons in JQuery without a class name or id

How can I target a button from a group of buttons without using a class or id, just n JQuery

Example:

<body>
  <button>Click Me</button>
  <button>Click Me</button>
  <button class="food">Click Me</button>
  <button>Click Me</button>
  <button>Click Me</button>
  <input type="text">
  <!--
     <script src="ajax.googleapis.com/ajax/libs/jquery/3.6.0/…>
     <script src="index.js"></script>
  -->
 </body>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With JQuery this would only be possible if the button’s had unique innerText or innerHTML that you could then predict.

Using my example HTML from below:

<div>
  <button>Button1</button>
  <button>Button2</button>
  <button>Button3</button>
  <button>Button4</button>
</div>

You would need to use JQuery to grab all tags, and then filter that by their innerHTML or innerText depending on what is inside the button tag.

See the below JS:

// Assuming you want 'Button 1'
for(let el of $("button")){
  if(el.innerText === 'Button1') el.addEventListener() // Then from here do the rest
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading