Array jQuery - Remove indices and concatenate html

3

I'm making an ajax call that retweets the Html of filters to be put on a particular div. However I would like to remove some html elements previously. For that I passed the html to jQuery, thus turning it into an array. After removing the elements you would like to resume the concatenated html.

I'm currently doing this:

msg = jQuery(msg);
var index = 0;
var html = '';
msg.each(function(i, _this){
    if(jQuery(_this).find('input[type="submit"]').size() == 1){
        index = i;
        return;
    }
});
msg.splice(index,2);
msg.each(function(){
    html += this.outerHTML
});

Example

But I'm not very happy with the development, would anyone know how to make this function better?

    
asked by anonymous 14.09.2015 / 22:47

2 answers

3

I'll give you two advices:

  • jQuery is not a mandatory tool for manipulating the DOM.
  • You do not need to recreate all the elements in order to remove a node.
  • var submits = document.querySelectorAll("p input[type='submit']")
    [].forEach.call(submits, function (elemento, indice) {
      elemento.parentNode.removeChild(elemento);
    });
    <p class="left">
    	<input name="teste1" type="text" />
    </p>
    <p class="left">
    	<input name="teste2" type="text" />
    </p>
    <p class="left">
    	<input name="teste3" type="text" />
    </p>
    <p class="left">
    	<input name="teste4" type="text" />
    </p>
    <p class="left">
    	<input name="teste5" type="text" />
    </p>
    <p class="left">
    	<input type="submit" />
    </p>
        
    14.09.2015 / 23:35
    0

    Using the response provided by @TobyMosque and searching a bit more.

    I came to this solution, which suits the case more, because as I commented the HTML comes via Ajax. Either it's a string, so basically I'd like to treat the string.

    var doc = new DOMParser().parseFromString(msg, 'text/html');
    var submits = doc.querySelectorAll("P input[type='submit']");
    [].forEach.call(submits, function (elemento, indice){
        elemento.parentNode.removeChild(elemento);
    });
    var htmlFinal = doc.body.innerHTML
    
        
    15.09.2015 / 14:03