开发者

jQuery: array of elements to raw html?

Let's say I have an array like this:

var content = [ $('<p>...<开发者_开发知识库/p>'), $('<p>...</p>') ];

I need to get the markup of the concatenated elements. So I need to convert content" into a raw string: "<p>...</p><p>...</p>".

How can this easily be done? Seems like there should already be something in the framework to do this.

Somehow maybe convert content into a document fragment and call .html() on the document fragment to get the markup?


Nothing automatic, but you could easily do what you just described.

Try it out: http://jsfiddle.net/Y5x5z/

var content = [ $('<p>...</p>'), $('<p>...</p>') ];

var container = $('<div/>');

$.each(content, function(i,val) {
    container.append(val);
});

alert(container.html());
  • http://api.jquery.com/jquery.each/
  • http://api.jquery.com/append/ ​


This is shorter than the other answers, works correctly, and does not use an explicit loop:

[$("<p>"), $("<p>")].map(function(el){return el.get()[0].outerHTML;})

As Crazy Train points out in the comments, this can be sugared-up as follows:

var content = [ $('<p>...</p>'), $('<p>...</p>') ];

$.fn.toString = function() {
    return this[0].outerHTML
};

alert(content.join("")); // <p>...</p><p>...</p>


I recently encountered the same type of task and today's way of doing this is simple:

const elements = [$('<p>...</p>'), $('<p>...</p>')];
const resultString = elements.reduce(
  (HTMLString, [element]) => HTMLString.concat(element.outerHTML),
  '',
);

Notice that HTMLString's default value in reduce is ''. It's important for HTMLString to be a type of string to be able to concatenate HTML strings of elements to it.


This is an old post someone may stumble upon it like me... the correct way to do it would be .join() (standard JavaScript not jQuery)

var content = [ $('<p>...</p>').html(), $('<p>...</p>').html() ];

var concatenatedHTML = content.join('');

//concatenatedHTML would then be '<p>...</p><p>...</p>'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜