JQuery: select an element from a parsed html fragment

Inside the class method, I parse the html fragment as follows:

    this.editCtrl = $('<input type="radio" name="society" value="existing"><select class="society"></select></input><input type="radio" name="society" value="existing"><input type="text"></input></input>');

I can add this snippet to my DOM, and everything works fine, but before doing this, I would like to populate a drop-down list. I tried to do this:

    var dropdown = this.editCtrl.find('select.society');

and like this:

    var dropdown = $('select.society', this.editCtrl);

The length of the result set is zero in both cases. What is the correct way to get a specific element from such a html fragment?

+3
source share
1 answer

You can use filterin this case:

$('<input type="radio" name="society" value="existing"><select class="society"></select></input><input type="radio" name="society" value="existing"><input type="text"></input></input>').filter(function() {
    return $(this).is('select.society')
})

The reason is that if you used find, you would need to be from your parent element <select>, otherwise you will directly look for elements, and not from above.

+6

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


All Articles