AndrewCoCo AndrewCoCo - 2 years ago 146
HTML Question

Target a div ID that appears on a page containing a specific class - CSS or jQuery? Both?

I'm very new at this, so please forgive me if I'm not explaining this correctly, or not providing the right code (or providing too much).

So near the top of my page I have this code:

<div id="javo-detail-item-header-wrap" class="container-fluid javo-spyscroll lava-spyscroll" style="padding: 0px; z-index: 1;">

And then further down the page:

<div id="post-2355" class="single-item-tab post-2355 property type-property status-publish has-post-thumbnail hentry property_type-ny property_status-sold">

I want to target
from the first line of code, but ONLY when
is also on the page.

From what I understand it's not possible to target an element via CSS by its descendant, right? I've seen mentions online of a similar situation being solved by renaming the first ID with jQuery - is that what needs to be done here?

IS the second element even a descendant of the first if it's not in the same div?

Answer Source

Without seeing your full code structure, I'd say 99% it's not possible using plain CSS. Doing it in JavaScript should be quite easy:

function getIt() {
  if (document.getElementsByClassName('property_status-sold').length > 0)
    return document.getElementById('javo-detail-item-header-wrap');

To get your element, just call the function getIt (and give it a better name) - it will return either the element reference, or undefined if either the .property_status-sold is not found or the actual element #javo-detail-item-header-wrap is missing for some reason.

If you really like jQuery that much, here's the above code (note that it returns a jQuery object, not the element reference - you can use .get(0) to the the element reference):

function getIt() {
  if ($('.property_status-sold').length > 0)
    return $('#javo-detail-item-header-wrap');

A quick-fix for hiding that element:

  if (jQuery('.property_status-sold').length > 0)

This is all you need.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download