Lemvig Kiggeren
Lemvig Kiggeren

Reputation: 317

jQuery select element but one child element

I am trying to apply some CSS on an element and all children but one. That includes strings outside elements as well. It's a tag I need to leave out of it, because I need to change the CSS on the tag to something else. I cannot do this:

$("div *").not("h1")[...]

because it does not apply to the strings.

http://jsfiddle.net/P5EAs/2/ and http://jsfiddle.net/P5EAs/1/ to see what I mean.

This is jQuery, so doing it with CSS does not work. I need to use .css()

Upvotes: 1

Views: 129

Answers (5)

ndpu
ndpu

Reputation: 22561

$("div").css("color","red").find("h1").css("color", "black");

Upvotes: 1

adeneo
adeneo

Reputation: 318202

You can not set color directly to textnodes, so you either have to set the red color on the parent, and specifically set the H1 to black color, or you'll have to wrap the textnode in a span, and set the red color on all children but the H1.

$('div').children(':not(h1)').css('color', 'red').end()
        .contents().filter(function() {
            return this.nodeType === 3;
        }).wrap('<span style="color: red" />')

FIDDLE

Upvotes: 0

codingrose
codingrose

Reputation: 15699

Try:

Only CSS:

div{color:red;}
div h1{color:black;}

Fiddle here.

Only JS:

$("div").css("color", "red");
$("div h1").css("color", "black");

Fiddle here.

Upvotes: 1

RononDex
RononDex

Reputation: 4183

The closest thing you could get is:

$("div > *:not(h1)").css("color", "red");

However this will ignore text that is not wrapped in an element

Upvotes: 0

bipen
bipen

Reputation: 36531

since h1 is a child of div you need to find children and use not.. try this

$("div").children().not('h1').css("color","red");

or,

with simple CSS

div{color:red;}
h1{color:black;} //after div..

this should work

Upvotes: 1

Related Questions