logo

jQuery selecting object that has an attribute

logo

jQuery is such a powerful, and fun, language to learn. There may be some situations where the same class is used on multiple objects, and there may be cases where you only want to target one particular type of objects despite the same class being used multiple times.

For example:

<table class="contentpaneopen">
<tbody>
<tr>
<td class="contentheading" width="100%">
<h1>MEMBERS</h1>
</td>
</tr>
</tbody>
</table>
<div class="contentheading">
<h2>Sub Heading</h2>
</div>
<div class="aLittleBox">

Just some example content

</div>

jQuery has an awesome way of differentiating from the two above examples, despite not having an ID and both having the same class:

jQuery(‘td[class|=contentheading]‘).css(‘color’,‘pink’);

Here we are targeting any td that has the class “contentheading” and changing the css colour of it! We can then even extend this to target items inside the object for example:

jQuery(‘td[class|=contentheading]‘).prepend(jQuery(‘.aLittleBox’));
jQuery(‘td[class|=contentheading] h1′).css(‘padding-bottom’,0);

You may not even know if the td object exists with this class name though, so you can do something like:

if(jQuery(‘td[class|=contentheading]‘).html()){
jQuery(‘td[class|=contentheading]‘).prepend(jQuery(‘.aLittleBox’));
jQuery(‘td[class|=contentheading] h1′).css(‘padding-bottom’,0);
}else{

//no td with the class "contentheading" on this page
}

3 Responses to “jQuery selecting object that has an attribute”

  1. Drew says:

    Interesting read! I often find situations where I need to do something and only jquery can save the day.

  2. Derek says:

    Only jQuery can save the day in my book. I just love this language, its so easy and fun to use, right?

  3. Chris says:

    Great post as usual. Well I expect nothing less from Timby’s Tech Talk. I can just simply copy the codes right off Timby’s post, awesome!

Leave a Reply

logo
logo
Powered by Wordpress | Designed by Elegant Themes