Recursively inspect HTML input elements

I wrote the following recursive input validator, and it works for me. Is there a better way to visit each dom element and check if this is an input field and confirm it?

function formValidator(parent) { //base case no children if( parent.children().length == 0) return //recurse through each childs' child parent.children().each(function(){ formValidator($(this)); /** * Work : check if this node is an input node */ if($(this).is("input")) { var type = $(this).attr('type'); if(type =="text") //do work bro } });//end for each } 
+6
source share
2 answers

If better you mean fewer details, this is equivalent to functionally

 parent.find('*').each(function(){ /** * Work : check if this node is an input node */ if($(this).is("input")) { var type = $(this).attr('type'); if(type =="text") //do work bro } });//end for each 

Note that there is no need for recursion, because

 parent.find('*') 

uses * (all-selector) . This will allow you to get all the children and nested children.

Update

To increase productivity, you can reorganize higher

 parent.find('input[type="text"]').each(function(){ var type = $(this).attr('type'); //if(type =="text") //above no longer needed });//end for each 

This will result in nesting all nested input elements, so you don’t even have to check

 if($(this).is("input")) 
+4
source

I would use a narrower selector:

 parent.children().find("input:text").each(function(){ // Valid $(this) element to validate }); 
+3
source

Source: https://habr.com/ru/post/987607/


All Articles