0

Is it possible to create something like a "DOM" in a variable? Right now I'm creating a temporary div-container, so I can append my results to the correct elements. After that I remove the temporary container.

But is this really necessary?

First of all I parse a HTML-string. After that I create a section-box (if the content matches with a keyword-array) and put some content in that section-box. That is how the code is working.

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(); // <--
user3142695
  • 15,844
  • 47
  • 176
  • 332

1 Answers1

0

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 plain string concatenation if you can since what will be faster

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531