Search code examples
javascriptjquerydominputchildren

Get all input of form from a html-string with jQuery - No matter which level they are


I want to extract out of an html string all forms and their input fields. In order to do this, I've written the following code:

var html = $.parseHTML("<html><form id="Form1"><div><input name="Input1"></div></form></html>");
$(html).find('form').each(function(e) {
    var FormElement = $(this);

    $(FormElement).find('input, textarea').each(function(e) {
        consolge.log($(this).attr('name') + " is an input field of a form with the the ID: " + $(FormElement).attr('id'));
    });
});

Sadly, this extracts only the children input fields of the form. The input fields, which are in a div, which is in a form are not affected by the scanning.

(working example: html -> form -> input)

(not working example: html -> form -> div -> input)

Any suggestions?

Thanks in advance! :)


Solution

  • I have updated your code to use (html).each()

    //with multipule forms
    var html = jQuery.parseHTML("<html><form id='Form1'><div><input name='Input1'></div></form><form id='Form2'><div><input name='Input2'></div></form></html>");
    
    jQuery(html).each(function(e) {
    
        var id = jQuery(this).attr('id');
        jQuery(this).find('input, textarea').each(function(e) {
            //that will output for every input and textarea
            console.log(jQuery(this).attr('name') + " is an input field of a form with the the ID: " + id );
    
        });
    });