nathanbweb
nathanbweb

Reputation: 717

css or jquery selector exclude child

How do I select the title but not the subtitle here:

<h1 id="banner">
This is the Title 
<span id="subtitle">and the subtitle</span>
</h1>

I'd like to do something like

h1 < span#subtitle {font-weight:bold}

or

h1:not(#subtitle) {font-weight:bold}

Upvotes: 0

Views: 620

Answers (3)

Oriol
Oriol

Reputation: 287990

See http://jsfiddle.net/PhSBE/

Just use

#banner{font-weight:bold} /* Title's rules */
#banner>#subtitle{font-weight:normal} /* Subtitle's rules */

Edit:

If you want to extract the text you could see https://stackoverflow.com/a/12135377/1529630

It's a function that extracts the text from an element, ignoring HTML elements.

Upvotes: 2

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91299

To extract just the title text, but not the subtitle, use the following:

var text = $("#banner").contents().filter(function () {
  if (this.nodeType == 3) { // Text Node
    return this;
  }        
})[0];

DEMO.

Upvotes: 2

Peter
Peter

Reputation: 16923

if you change h1 to bold, you need to change span to normal, because child elements are inherting css from parents

If you want to make some attributes to This is the Title only you need to make another <span> for it.

Upvotes: 1

Related Questions