Marxtai Marxtai - 6 months ago 11
Javascript Question

Find children of a certain type

I have an array of all the

forms
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){
e.preventDefault();
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
id
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
id
or anything else that could be used to differentiate them when using
querySelectorAll()
.

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');

Answer

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");

Demo

let forms = document.querySelectorAll("form");
[].forEach.call(forms,form=>{
   form.querySelector("button").innerText += " - Modified";
});
<form>
  <button>A button</button><br>
  <input><input>
</form>
<form><br><br>
  <button>B button</button><br>
  <input><input><br>
  <button>C button</button>
</form><br><br>
<form>
  <button>D button</button><br>
  <input><input>
</form>

Comments