简体   繁体   中英

How to use html() of jquery over specific child element

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM