简体   繁体   中英

Getting a HTML element DOM as string using javascript without child elements

I was wondering if there was any method to get a html element / node without its children as a string.
This question might seem like a duplicate of this question: jQuery, get html of a whole element .
But i only want the html element itself as a string, without its children.

texts.push({title:'[#target, outerHTML]', value: $input[0].outerHTML});
texts.push({title:'[#target, $.html()]', value: $input.html()});

texts.push({title:'[#bigger_Target, outerHTML]', value: $('#bigger_Target')[0].outerHTML});
texts.push({title:'[#bigger_Target, $.html()]', value: $('#bigger_Target').html()});

texts.push({title:'[#target, DESIRED]', value: '<input class="test" data-type="text only" type="button" value="Test />"'});
texts.push({title:'[#bigger_Target, DESIRED]', value: '<div id="bigger_Target" />'});

FIDDLE:
http://jsfiddle.net/ttoom9hc/12/

FIDDLE FROM OTHER POST:
http://jsfiddle.net/u6avkvz0/

The easiest way I can think of is to clone it shallow with DOM's cloneNode , then get the outerHTML of that:

var element = $("selector for the element you want");
var html = element[0].cloneNode(false).outerHTML;

Example (made my own, wow was that fiddle complex)


Or with more jQuery: Example

var html = $("selector for the element you want")
               .clone()
               .contents()
               .remove()
               .end()[0].outerHTML;

Note that the text inside the element is "child" content (specifically, one or more Text node children). If you want those, you'll need a loop. jQuery's contents can help there: Example

var html = $("selector for the element you want")
        .clone()
        .contents()
        .each(function() {
          if (this.nodeType !== 3) { // It's not a Text node...
            $(this).remove();        // ...nuke it
          }
        })
        .end()[0].outerHTML;

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