Leslie Optional
Leslie Optional

Reputation: 178

JQuery - How to get all the *html* of elements excluding one

This is an example of the HTML:

   <div id="block1">
   <div class="header">
   <span category="drink" class="uservar">TEQUILA</span>&nbsp; &nbsp; 
   <span class="block-controls" style="height:15px" contenteditable="false">
   <span title="delete block"><span placeholder="remove block" class="remove">X</span>
   </span>
   </div>
   </div>

I want to have a selector that returns everything within the .header div before the "block-controls" child. Sometimes there will be other html elements in the header (as above) before the "block-controls" and sometimes it will be just text (no span, just the word 'Tequila'. It needs to work in both cases.

This return the text TEQUILA, but not span tag.

$('#block1 .header').children().not('.block-controls').html();

Upvotes: 0

Views: 166

Answers (2)

dereli
dereli

Reputation: 1864

What you need is outerHtml:

(function( jQuery, undefined ) {
    jQuery.fn.extend({
        outerHtml: function() {
            var html = "";
            this.each(function() {
                html += jQuery( "<div>" ).append(jQuery( this ).clone()).html();
            });
            return html;
        }
    });
})( jQuery );

alert($('#block1 .header').children().not('.block-controls').outerHtml());

Check this fiddle: http://jsfiddle.net/29eBn/1/

Upvotes: 1

PeterKA
PeterKA

Reputation: 24638

This will give you the text your specified:

    var div = $('<div/>');
    $('#block1 .header').children().not('.block-controls').appendTo( div );
    var x = div.html();

JS FIDDLE DEMO

OUTPUT: <span category="drink" class="uservar">TEQUILA</span>

EDIT

The code has been edited to remove && this.nodeType !== 3 as that was addressing nodes that aren't even there!

Demo is updated too.

Further updated per comments below.

Upvotes: 1

Related Questions