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

Time:06-23

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

CodePudding user response:

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
}

CodePudding user response:

There many ways, You can use onclick method inline Html. A crude way---

<script>

function function1(){

alert ('Button1')
}

function function2(){

alert ('Button2')
}
function function3 (){

alert ('Button3')
}

</script>
</head>
<body>

<button onclick="function1()">Button 1</button>

<button onclick="function2()">Button 2</button>
<button onclick="function3()">Button 3</button>
</body>
  • Related