-1

I am trying to select a div and change its background image but only if the a element before it exists and has a certain ID. See the following:

<td class ="thumbnails">
<a name="abc" id ="def"></a>
<div class="bgimages"></div>
</td>

How would I select and change the background image of the div with class 'bgimages' based on whether or not it has the a element before it with the ID 'def'?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
tmnsnmt
  • 95
  • 1
  • 10

2 Answers2

2

There is no reason to use jQuery or javascript for this, you can do with only CSS. See below example with colors.

.bgimages {
    background-color: green;
}

#def + .bgimages {
    background-color: orange;
}
<table>
  <tr>
    <td class ="thumbnails">
      <a name="abc" id ="def">yyyy</a>
      <div class="bgimages">yyyy</div>
    </td>
  </tr>
  <tr>
    <td class ="thumbnails">
      <a name="abc" id ="defxxx">yyyy</a>
      <div class="bgimages">yyyy</div>
    </td>
  </tr>
</table>

Replace background-color with background-image

caramba
  • 21,963
  • 19
  • 86
  • 127
2

You can select the div element with a def id anchor before as such;

console.log($("a#def").next("div.bgimages"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class ="thumbnails">
<a name="abc" id ="def"></a>
<div class="bgimages"></div>
</td>
buræquete
  • 14,226
  • 4
  • 44
  • 89