Marxtai Marxtai - 4 months ago 7x
Javascript Question

Find children of a certain type

I have an array of all the

in my page. I want to iterate through all the forms, and find the buttons in them. How can I achieve this in Javascript alone, without any libraries?

Here's my JS code :

var forms = document.querySelectorAll('form');

for(var i = 0; i < forms.length; i++;){
var form = forms[i];
form.addEventListener('submit', validateForm);

function validateForm(e){
var button = ?; // I want to get the button that is a child of this form

I know that I can use this to get all the buttons that are children of a form :

var buttons = document.querySelectorAll('form button');

But how can I get just one button that is a children of this form?

I've seen this question asked multiple times, but it was always to find the children of a parent that was known, with a specific
or something like that. I have no idea how many forms there will be in the page, and I have no control on wether or not they have unique
or anything else that could be used to differentiate them when using

Is it possible to achieve what I want?

I'm looking for the pure JS alternative to this in jQuery :

var $form = $('form');
var $childButton = $form.find('button');


Element has equivalent versions of querySelector/All and so can be called from elements as well as document. So if you are looking for a button inside a form element you can just call querySelector from the form element

var form = document.querySelector("#SomeForm");
//Will find the first button in the form
var someBtn = form.querySelector("button");
//Will find all buttons in the form.
var someBtns = form.querySelectorAll("button");


let forms = document.querySelectorAll("form");
   form.querySelector("button").innerText += " - Modified";
  <button>A button</button><br>
  <button>B button</button><br>
  <button>C button</button>
  <button>D button</button><br>