简体   繁体   中英

jQuery attribute Selectors Issue

I am have an issue with jQuery attribute selector, I can't understand why "Div 1" got the green background color in this example.

 $(document).ready(function() { $('div[title],[style]').css('border', '5px solid red'); $('[title][style]').css('background-color', 'green'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div title="div1Title"> Div 1 </div> <p title="p1Title"> Paragraph 1 </p> <div style="background-color:yellow"> Div 2 </div> <p title="p2Title" style="background-color:yellow"> Paragraph 2 </p> 

Because your first line causes addition of style attribute to your div1 , this line

$('div[title],[style]').css('border', '5px solid red');

and so your div1 now have title as well as style attribute both and so the next line this

$('[title][style]').css('background-color', 'green');

applies to it.

If you don't want to apply background color to your first div, just switch the order of your lines

This line:

 $('div[title],[style]').css('border', '5px solid red'); 

This line takes every element with a style attribute and every div element with a title attribute and sets its inline style to have a border.

It matches the div because it has a title attribute.

Then this line:

 $('[title][style]').css('background-color', 'green'); 

Sets the background colour of every element with a title and a style attribute to green.

It matches the div because it started with a title attribute and the previous line added a style attribute.

I can't understand why "Div 1" got the green background color

Because your first rule, $('div[title],[style]').css('border', '5px solid red'); says select all divs that have a title attribute and all elements with a style attibute and give them a 5px solid red border. jQuery does this by applying the CSS inline, so the divs that have the title attribute will now also have an inline style attribute.

At this point your second rule $('[title][style]').css('background-color', 'green'); will select all elements with both a title and style attribute, which includes Div 1.

Very simple, this is what's happening:

1-

$('div[title],[style]').css('border', '5px solid red');

Sets an inline style on the div s that don't have style , but have either title or any element that has style , but setting an inline style creates style on the div s without style .

2- So those div s with newly set style on them are also selected by

$('[title][style]').css('background-color', 'green');

And you see the green background color on them.

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