Reputation: 175
<table>
<tr>
<td><a href src="xxx" title="Some text">Link</a></td>
<td><a href src="xxx" title="">Link</a></td>
</tr>
<tr>
<td><a href src="xxx" title="Some text">Link</a></td>
<td><a href src="xxx" title="Some text">Link</a></td>
</tr>
</table>
I want to add some CSS class to
<td><a href src="xxx" title="">Link</a></td>
How can I make this with jQuery or JavaScript
Upvotes: 5
Views: 164
Reputation: 87203
No need of using jQuery to add a CSS class. You can use attribute-value selector in CSS.
a[title=""] {
color: red;
}
To add class by using jQuery other than just styling purpose
$('a[title=""]').addClass('someClass');
To select elements which do not have title
attribute
a:not([title]) {
color: red;
}
Same selector can be use in jQuery.
$('a:not([title])')
Upvotes: 8
Reputation: 3578
As the other answers have pointed out, you can achieve this with css. However, if you are set on using javascript or jQuery, you could use the following;
note - I do not recommend this solution, I have posted this purely because you asked for a javascript/jQuery solution. Go with the CSS only option.
var links = document.getElementsByTagName('a');
for(var l = 0; l < links.length; l++){
if(!links[i].hasAttribute('title')){
// Link without title attribute
links[l].style.color = 'red';
// Or if you want to add a class...
links[l].setAttribute('class', links[l].getAttribute('class') + 'red');
}
}
Upvotes: 0
Reputation: 67207
How can I make this with jQuery or JS
You can do it with attribute equals selector
,
$("table > tbody > tr > td > a[title='']").addClass("something");
Also note that you have an invalid html, tbody
should be the immediate child of a table
element.
<table>
<tbody> <!-- note the tbody here -->
<tr>
<td><a href src="xxx" title="Some text">Link</a></td>
<td><a href src="xxx" title="">Link</a></td>
</tr>
<tr>
<td><a href src="xxx" title="Some text">Link</a></td>
<td><a href src="xxx" title="Some text">Link</a></td>
</tr>
</tbody>
</table>
Upvotes: 1