Get selected element's outer HTML

前端 未结 30 2346
礼貌的吻别
礼貌的吻别 2020-11-21 04:50

I\'m trying to get the HTML of a selected object with jQuery. I am aware of the .html() function; the issue is that I need the HTML including the selected obje

30条回答
  •  情歌与酒
    2020-11-21 05:22

    No need to generate a function for it. Just do it like this:

    $('a').each(function(){
        var s = $(this).clone().wrap('

    ').parent().html(); console.log(s); });

    (Your browser's console will show what is logged, by the way. Most of the latest browsers since around 2009 have this feature.)

    The magic is this on the end:

    .clone().wrap('

    ').parent().html();

    The clone means you're not actually disturbing the DOM. Run it without it and you'll see p tags inserted before/after all hyperlinks (in this example), which is undesirable. So, yes, use .clone().

    The way it works is that it takes each a tag, makes a clone of it in RAM, wraps with p tags, gets the parent of it (meaning the p tag), and then gets the innerHTML property of it.

    EDIT: Took advice and changed div tags to p tags because it's less typing and works the same.

提交回复
热议问题