Rohit Verma
Rohit Verma

Reputation: 3785

Why i'm getting just text instead of HTML using JQuery?

I have a H1 tag & i want to get HTML() of this element on button click but right now getting just text instead of HTML. How can i get proper HTML?

My Code:-

$(function(){
  $('button').click(function(){
    alert($('h1').html());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 style="color:indianRed">Heading 1</h1>

<button>Click</button>

Upvotes: 0

Views: 53

Answers (3)

Mamun
Mamun

Reputation: 68933

You should use outerHTML:

The outerHTML attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.

$(function(){
  $('button').click(function(){
    alert($('h1').get(0).outerHTML);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 style="color:indianRed">Heading 1</h1>

<button>Click</button>

Upvotes: 3

Matan Sanbira
Matan Sanbira

Reputation: 1513

outerHTML in javascript

$(function(){
$('button').click(function(){
  alert(document.querySelector("h1").outerHTML);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 style="color:indianRed">Heading 1</h1>

<button>Click</button>

Upvotes: 1

M0ns1f
M0ns1f

Reputation: 2725

The .html() function return the inner html of an element, to get the outerHTML of any given element, try to wrap it inside a container then get his html using .html().

$(function(){
  $('button').click(function(){
        var elHTML = $('<div></div>').append($('h1'));
       alert(elHTML.html());
   });
 });

Upvotes: 0

Related Questions