Using the Spry javascript framework (or a compatible methodology), is there some way to change the class of a specific element's parent element even if that parent doesn't have an ID set? For example, given this:

<span><img src="image-book_s-1.jpg" id="imgBook1" /></span>

...I want to set the class of the span to "bookSelected" programmatically by clicking on another element.

Is there a CSS selector to represent this relationship that I could pass to a javascript function?

2 answers

Mottie 1134
2
points
This was chosen as the best answer

I've never used the Spry library before, but it doesn't look very user friendly to me. I'd recommend looking into jQuery. Either way, I think I've pieced together something that should work for you.

<a href="#" onclick="javascript: addClass()">Add Class</a>
<span><img src="image-book_s-1.jpg" id="imgBook1" /></span>

<script type="text/javascript">
function addClass(){
 var el = document.getElementById('imgBook1').parentNode;
 Spry.Utils.addClassName(el,'bookSelected');
 return false;
}
</script>

In jQuery it would look like this (notice I don't need to modify the HTML):

<!-- it would be better to add a class to the link if possible, e.g. <a href="#" class="addit">Add Class</a> -->
<a href="#">Add Class</a>
<span><img src="image-book_s-1.jpg" id="imgBook1" /></span>

<script type="text/javascript">
$(document).ready(function(){
 $('a:contains("Add Class")').click(function(){ // it would be better to add a class to the link and reference it, e.g. $('.addit').click(function(){
  $('#imgBook1').parent().addClass('bookSelected');
  return false;
 })
})
</script>
Answered almost 7 years ago by Mottie
1
point

You can append CSS to a parent using the parentnode dom element.
....

if (node.parentnode) {
      element.setAttribute('mycssclass'); 
}
Answered almost 7 years ago by Tallboy