Suchi
Suchi

Reputation: 10039

jQuery - how to put html elements on page using javascript

I am a jQuery newbie. I am trying to do something like this:

function putJStorageValues () { 
  var keys = getJStorageValues();
  var test = "";
  jQuery.each(keys, function(index, item) {
    test += "<br>" + item;
  });
  $("#storageValues").text(test);
}

But this ends up with "
myItem". How would I print HTML such that there is a line break and then the item?

Upvotes: 1

Views: 77

Answers (4)

Adil
Adil

Reputation: 148150

You better use .html method as you have <br/> in text or you might expect other html elements in the text.

$("#storageValues").html(test);

.html() - This jQuery function gets/sets the HTML of any element. .text()- This jQuery function gets/sets the text (innertext) of any element. Details

function putJStorageValues () {

var keys = getJStorageValues();
var test = "";
jQuery.each(keys, function(index, item) {
    test += "<br>" + item;
});
$("#storageValues").html(test);
}

Upvotes: 2

Travis J
Travis J

Reputation: 82297

Usually DOM manipulation is done with the appendChild function, or append in jQuery. This requires the creation of DOM elements to append.

function putJStorageValues () {

 var keys = getJStorageValues();
 jQuery.each(keys, function(index, item) {
  var toInsert = document.createElement("p");
  p.innerHTML = item;
  $("#storageValues").append(toInsert);
 });
}

Upvotes: 1

Chad Ferguson
Chad Ferguson

Reputation: 3091

You will want to use append()

function putJStorageValues () {

     var keys = getJStorageValues();
     var test = "";
     jQuery.each(keys, function(index, item) {
          test += "<br>" + item;
     });

     $("#storageValues").append(test);
}

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

$("#storageValues").text(test); <-- this puts text on an element (strips HTML) $("#storageValues").html(test); <-- this puts HTML in an element

Upvotes: 4

Related Questions