Abdelrahman Abdelrahman - 6 months ago 14
Javascript Question

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>




Answer

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