CWood
CWood

Reputation: 3

How can I jQuery select a child div element?

I'd like to select a page element based on the 'id' of a parent, plus the 'class' of one of its children. This works when the child is a span element, but fails when it's a div.

How can I select the specific #testDiv .highlightme item below?

<script>  
        $(document).ready(function(){  
        $('#testSPAN .highlightme').css("background-color","yellow");  
        $('#testDIV  .highlightme').css("background-color","blue");  
    });  
</script>  



<p id="testSPAN">
    <span class="highlightme">
        This should highlight, and does. Good.
    </span>
</p>

<p id="testDIV">
    <div class="highlightme">
        This should highlight, but doesn't because it's in a div.
    </div>
</p>

Upvotes: 0

Views: 70

Answers (3)

Allan
Allan

Reputation: 261

What have been told here, it's true, you should not put block elements inside inline elements, but if you can't modify the html or you are not allowed, here is a little work around that will work for you...

$(document).ready(function(){
    $('[id*="test"]').each(function() {
        var bgcolor = "yellow";
        if ($(this).children('[class="highlightme"]')   ) {
            $(this).children('[class="highlightme"]').css('background-color', bgcolor);
        }
        if ($(this).next().hasClass("highlightme") == true) {
            $(this).next().attr('class', 'highlightme').css('background-color', bgcolor);
        }
    });
});

I hope this little block of code helps you out, if you need anything else, just let me know ;)

Upvotes: 0

Xiu
Xiu

Reputation: 125

It doesn't matter whether it's a div or span. You can attribute a class element to any markup.

The problem is not because of your jquery code but you wrap your div element within a p it's not allowed in html ! :)

Upvotes: 0

BReal14
BReal14

Reputation: 1584

A p tag only takes inline elements, not other blocks. http://www.w3.org/TR/html401/struct/text.html#edef-P "The P element represents a paragraph. It cannot contain block-level elements (including P itself)."

This is the core of your problem, it is invalid HTML.

Upvotes: 3

Related Questions