0

I'm just trying to change the background color of all "h1" elments present under "p" as below but it's not working

$(document).ready(function(){



    $("p").find("h1").css("background-color","yellow");

});

Below is jsfiddle

http://jsfiddle.net/sukumar/X9yQL/4/

JavaGeek
  • 1,535
  • 9
  • 39
  • 63
  • 5
    I think this fails because your markup is invalid – David Snabel-Caunt Jul 11 '11 at 14:52
  • 3
    You should know that having a header tag inside a paragraph tag is invalid html. W3C validator wouldn't validate it. – kei Jul 11 '11 at 14:53
  • 1
    Don't put block elements like `h1` in inline elements like `span`. – Radu Jul 11 '11 at 14:56
  • @Radu strangely, chromium doesn't have problem with h1 inside a span, but can't accept it inside a "p". doesn't know if it's standard compliant since you can play so easily with inline/block display in css – BiAiB Jul 11 '11 at 14:59
  • I don't believe that an `

    ` tag is legal within a `

    ` tag, according to this: https://developer.mozilla.org/en/HTML/Element/h1. I tried to play with your fiddle to give you an answer, but it seems to be doing strange things with a header within a paragraph.

    – FishBasketGordo Jul 11 '11 at 14:59
  • @BiAiB, most browsers will still render block elements within inline ones but it's bad practice. For that matter, headings within other headings isn't a good idea.. nor does it make sense :P – Radu Jul 11 '11 at 15:02
  • @Radu keeping semantics in your html structure is quite hard sometimes :p. Anyway I'm not sure of this but sometimes you have to do it in some CSS menus because IE won't understand :hover pseudo class in anything but anchors elements. – BiAiB Jul 11 '11 at 15:07

3 Answers3

6

your html markup is invalid. Look at the markup generated with a debugger:

  <p>first
    </p><h1>first h1 <span>span1

        <h1>another h1 inside span</h1>
        </span>
    </h1>




<p></p>

seems you can't have a h* inside a p

BiAiB
  • 12,932
  • 10
  • 43
  • 63
3

See Nesting block level elements inside the <p> tag… right or wrong?:

No, a paragraph element may not contain other block elements.

Reference

A paragraph tag is intended for a block of text. If your elements is a part of the text (and not block elements), it would be semantically correct, otherwise not. A span tag with display:block is still a block element.

Community
  • 1
  • 1
Michael Levy
  • 13,097
  • 15
  • 66
  • 100
1

Most browsers are going to remove the h1 tags from the p tags so it's not going to work. Using a span and styling it like an H1 will work just as good. Also your markup was a bit chaotic, I would suggest cleaning it up.

brenjt
  • 15,997
  • 13
  • 77
  • 118