1

I am trying to use html() function of jquery over the specific child like:

<div id="main">
  <p>I am p tag</p>
  <span> i am span tag</span>
</div>

Now if we use $("#main").html() it gives both p and span but if i want only p, what should i do?

Sirko
  • 72,589
  • 19
  • 149
  • 183
King Kong
  • 2,855
  • 5
  • 28
  • 39

2 Answers2

4

Try like below,

$("#main p").html()

This will give me I am p tag but i want <p> I am p tag</p>

Try below for outerHTML,

$('#main p')[0].outerHTML

Or you can make it as jQuery function so you can chain.

jQuery.fn.outerHTML = function(s) {
    var _this = this[0];
    return _this.outerHTML?_this.outerHTML:(s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html());
};

$('#main p').outerHTML()

DEMO: http://jsfiddle.net/skram/PMjKR/1/

Ref: Get selected element's outer HTML

Community
  • 1
  • 1
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • This will give me `I am p tag` but i want `

    I am p tag

    `
    – King Kong Jun 14 '12 at 16:10
  • he needs to get the html including the p tag.. by doing your method it would return the html contents **within** the `

    ` in which case there is not html, just text. You need to use outerHTML
    – NDBoost Jun 14 '12 at 16:15
2

Many ways depending on your exact requirements.

Standard css selector:

$('#main p').html();

filtering on children.

$('#main').children('p').html();

by getting the first child of main

$('#main:first-child').html();

EDIT after seeing comment on another answer by OP i will simply add where html() is replace with [0].outerHTML

see selectors here

AbstractChaos
  • 4,211
  • 1
  • 19
  • 28