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>

>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
}

Leave a Reply