+ 2
How can I target a button
17 Antworten
+ 4
You can give it an ID, and refer to it using JavaScript's getElementById method
+ 2
btns=[...document.querySelectorAll('button')]
btns[0].onclick=()=>{
alert('hi')
}
you can target each button by the array index of the particular button.
+ 1
<button onclick="function_name()">
</button>
+ 1
tanks a lot
+ 1
If you want to target a button, using JavaScript, you have to use 'click events' to fire an event to an element of html, this happens, when you click on something with your mouse by the browser. There are many ways to attaching it, you can use the querySelector, getElementById, getElementsByClassName, getElementsByTagName, these are method of JavaScript, so, you can use whatever you want, for example, you can store your html button in a variable and attach it with the querySelector, let button = document.querySelector('button'), in this example, we are using the button element of html, not the class or id and then, you can use the onclick handler to fire it up with the anonymous function and get a result. I hope this can help you, but you can find more information about 'click event' on https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics
0
in js you can use document.get
ElementByTagName("button")
that will give you access to an array of all buttons
0
or you can give your button an id
and use getElementById
in js
0
inside of <script> here!</script>
u can use it its a javascript function
0
like this
<script><button>test note</button></button>
0
what do u mean of targeting button?
0
i meant this
<script>document.getElemntByName(button)</script>
0
I mean, when you press the button, it shows a function
0
ur welcome
0
can you ask my text question?
0
tanks a lot
0
You may have many button on your web page, even ten.. But in your case you don't want to target all of them, maybe just one or a group of buttons... Imagine that you have something like this :<button id="me" >Say Hello</button><button>Bye</button><button>Close</button>. We have 3 buttons. So if want to target only the button that have the ID of "me", so that when the user triggers a click, the window objet alert "hello" message. So in my script tag, I'll do the following :
var helloButton =document.getElementBy("me");
Now let add our click event to above targeted button with id of "me" : helloButton.addEventListener('click',function() {
alert("Hello") ;
})
I hope I've helped
- 2
is getElementById a tag?