简体   繁体   中英

Target the child only not the sub-child by Jquery

If I have the following Markup

<div class='parent'>
  <div class='first'>
    First Child
    <div class='second'>
  Sub-child
    </div>
  </div>
</div>

and Below is Jquery

$('.parent').children().css("color","#00b3ff");

In result it changes color of both child,as I want to select the First child only (not by class).

how about something like this:

$('.parent').children().css('color', '#00b3ff').find('> div').css('color', 'black')

By using '>' the rule will be applied only on the immediate children, rather than all the children (when using .children())

Another thing you need to do is to ensure the child will not inherit the parent's color, can be done by explicitly giving it color.

Here's JSFIDDLE

You can't simply do it like that, the css properties are inherited by the chidlren - so if you apply a color to first it will get inherited by second since it is a decedent of first

Since we cannot apply style to text nodes a possible solution is to wrap the text node with an element and style it as given below

$('.parent > div').contents().filter(function(){
    return this.nodeType == 3 && $.trim($(this).text()).length > 0;
}).wrap('<span />').parent().css('color', '#00b3ff');

Demo: Fiddle

DEMO

var sel = $('.parent').children();
var old_color = sel.css('color');
sel.css('color', '#00b3ff');
sel.children().css('color', old_color);

No one post it, so, using only CSS:

DEMO

.parent > div{
    color:#00b3ff;
}
.parent div div {
    color:black;
}
$('.parent').next('div').css("color","#00b3ff");
    $(".parent > div:eq(0)").css("color","#00b3ff");
    $(".parent > div:first").css("color","#00b3ff");
$('.parent').children( '.first' ).css("color","#00b3ff");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM