Coverting jquery DOM to html

2019-09-04 23:04发布

问题:

I have the following jQuery DOM :

var markup = $("<a></a>").addClass("ClassName")
            .attr({ href : "Something.html",title : "Edit"});

I want to convert the above jQuery DOM(markup variable) to html . How to do the same?

回答1:

Either get outerHTML property of dom element

var markup = $("<a></a>").addClass("ClassName")
  .attr({
    href: "Something.html",
    title: "Edit"
  });

console.log(
  markup[0].outerHTML
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Or wrap by an element and get html content using html() method.

var markup = $("<a></a>").addClass("ClassName")
  .attr({
    href: "Something.html",
    title: "Edit"
  });

console.log(
  $('<div/>', {
    html: markup
  }).html()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



回答2:

To get the HTML you can wrap() it in another object, then retrieve the html() from that:

var $markup = $("<a></a>", {
    'class': 'ClassName',
    'href': 'Something.html',
    'title': 'Edit'
});
var html = $markup.wrap('<div />').parent().html();

Alternatively you can retrieve the outerHTML property of the underlying DOMElement:

var html = $markup[0].outerHTML;

Also just FYI, the term is a 'jQuery object'. There's only one DOM on the page.