Reputation: 335
is there a possibility to select an element but without one of the elements thats nested inside, if id-s of both elements are known?
like:
<div id="outerdiv">
<div>
<div id="innerdiv1"> </div>
<div id="innerdiv2"> </div>
</div>
</div>
i want to do a select which would return the outerdiv but without innerdiv2 like this:
<div id="outerdiv">
<div>
<div id="innerdiv1"> </div>
</div>
</div>
is there a statement like $('#outerdiv').not('#innerdiv2') or something that would do the trick? i can solve this using clone() + remove(), but im just wandering is there a chance to do it this way..
thanks
Upvotes: 4
Views: 7715
Reputation: 49188
I thought at first you could do this with selectors, but if you want the html structure, I believe you will need to actually have an html structure, not a list of matching elements by #selector. To wit:
$(document).ready(function(){
var clone = $('#outerdiv').clone()
$(clone).hide();
$('body').append(clone);
$(clone).attr('id','cloneddiv');
$('#' + $(clone).attr('id') + ' #innerdiv2').remove();
console.log($(clone));
$(clone).remove();
});
The console.log() refers to Firebug's console logging tool. This gets what you are looking for, in a way.
I would like to note, someone else had an answer like this, but they deleted it. Not sure why...
Upvotes: 1
Reputation: 14487
Here you are,
$('#outerdiv div:not(#innerdiv2)')
with outer div included:
$('#outerdiv div:not(#innerdiv2),#outerdiv')
It is actually a valid CSS3 selector, it works in jQuery too.
To answer to your comment I've made a little test in browsers console:
a = $('<div id="a"><div id="wrap"><div id="one"></div><div id="two"></div></div>')
a.find('div:not(#two)').addClass('a')
Result:
<div id="wrap" class="a">
<div id="one" class="a"></div>
<div id="two"></div>
</div>
The html()
method prints HTML content of first matched element of the selected stack. Your selected stack looks something like: [#outerdiv, div, #innerdiv1]. So html()
will show html for of #outerdiv
. If you need to generate HTML without #innerdiv2
, then you need to detach it:
$('#innerdiv2').detach()
$('#outerdiv').html()
Upvotes: 6