Add items to a variable instead of a temporary DOM

Is it possible to create something like "DOM" in a variable? Right now I am creating a temporary div container, so I can add my results to the right elements. After that I delete the temporary container.

But is it really necessary?

First of all, I am parsing the HTML string. After that, I create a section (if the content matches the keyword array) and put some content in this section. This is how the code works.

var elements = $.parseHTML(input_string);
var keywords = ['keyword1', 'keyword2'];
var existing = 0;

$("body").append('<div id="temp"></div>'); // <--

$.each(elements, function(index, element) { 
var z = element.innerHTML.trim();

    if ( $.inArray(z, keywords) !== -1) {
        $("#temp").append( '<section class="box"><h1>'+z+'</h1></section>' );
        existing = 1;
    }
    else {
        (existing) ? $("#temp .box:last").append( '<p>'+z+'</p>' ) : $("#temp").append( '<p>'+z+'</p>' );
    }

});

var result = $("#temp").html();
$("#temp").remove(); // <--
0
source share
1 answer

You can,

var elements = $.parseHTML(input_string);
var keywords = ['keyword1', 'keyword2'];
var existing = 0;

//create an element but do not append to dom
var $temp = $('<div id="temp"></div>');

$.each(elements, function (index, element) {
    var z = element.innerHTML.trim();

    if ($.inArray(z, keywords) !== -1) {
        //use the temp variable instead of dom lookup to access the temp object
        $temp.append('<section class="box"><h1>' + z + '</h1></section>');
        existing = 1;
    } else {
        (existing) ? $temp.find(".box:last").append('<p>' + z + '</p>') : $temp.append('<p>' + z + '</p>');
    }

});

var result = $temp.html();

But I would recommend using normal string concatenation if you can, since it will be faster

0
source

All Articles