Using 'title' attribute to change css elements
Just trying to get it to rearrange each element based on the content inside the header so far it only changes it based on the first and ignores the others. When I use "each ()" it should check each one and then change the color to red, without blue to yes.
<html>
<head>
<title>colorme</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2 /jquery.js"></script>
<script>
$(document).ready(function(){
$(".test").each(function(){
var title = $(this).find('.taskName').attr("title");
if(title =="yes") {
$('div.taskName').css('color','blue');
}
else if(title =="no") {
$('div.taskName').css('color','red');
}
});
});
</script>
</head>
<body>
<div class="test">
<div class="taskName" title="yes">this should be blue</div>
<div class="taskName" title="no">this should not be blue</div>
<div class="taskName" title="yes">this should be blue</div>
<div class="taskName" title="no">this should not be blue</div>
</div>
</body>
</html>
source to share
.attr
will only select the first attribute found. $("div.taskName")
also affects all attributes. You need to iterate over each one to get the title and get the correct div to update. You can do it right away:
$(".test").each(function(){
$(this).find('.taskName').each(function () {
var title = $(this).attr('title');
if ('yes' == title) {
$(this).css('color', 'blue');
}
else if ('no' == title) {
$(this).css('color', 'red');
}
});
});
source to share
Here's some good code:
$(document).ready(function(){
$(".taskName").each(function(){
var title = $(this).attr("title");
if(title =="yes") {
$(this).css('color','blue');
}
else if(title =="no") {
$(this).css('color','red');
}
});
});
Your error occurred because you were using div.taskName
jQuery as the selector. As a result, it is intended for all taskName, not just the current one.
To do this, you need to use the "this" keyword, so that every time the loop starts, it targets a different element.
I also changed the purpose of the loop. This way you don't need to use the function find()
. It's faster.
source to share