stuff.....Wh...">

JQuery by creating an HTML block that I can insert into a page

I have the following html:

<div id="box">
<span>stuff.....</span>
</div>

What I would like to do is create a JavaScript variable with this html ... Then with jQuery you can paste this into a page with something like $('#contentCol').html(mystuff)

Is there an elegant way to do this and not a long html string?

+3
source share
3 answers

Name identifiers are unique, so I changed id="box"to class="box", so you can insert a block multiple times.

Just create a function that returns the jQuery object of the type you want. You can pass HTML inside the function interval as an argument:

function createBlock(myHTML) {

    $("<div/>").attr("class", "box").append($("<span/>").html(myHTML));
}

You can use this function in several ways:

// Method 1:
var myStuff = createBlock("stuff");
$("body").append(myStuff);
  // or even...
$('#contentCol').html(myStuff)

// Method 2:
$("body").append(createBlock("other stuff"));

// You can of course append wherever you want... or prepend, or before / after
//   or use the jQuery object to build up an even larger block before inserting.

JsFiddle example

+6
source

javascript createElement appendChild .. DOM . jQuery

jQuery('<div id="box">...</div>').appendTo('#contentCol');
0

his work is for me

in the html file there is a div like

<div class="demo">
  <div class="demo">Demonstration </div>
</div>

and the class selector is .demo '

$('.demo').html('<form>Name:<input type="text" id="name">'+
        '<br>Pass:<input type="text" id="pass">'+
        '<br><input type="submit" value="confirm"></form>');

replace "<div class="demo">Demonstration </div>"with

"<form>Name:<input type="text" id="name">'+
        '<br>Pass:<input type="text" id="pass">'+
        '<br><input type="submit" value="confirm"></form>"
0
source

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


All Articles