Search code examples
javascriptjqueryhtmlcssparent

Implementing a parent selector in CSS with jQuery that applies automatically to new elements in DOM


CSS does not support parent selectors, e.g. "select all <p> that contain an <img>".

One solution proposed here is to use jQuery, for example:

$('#parent:has(#child)').addClass('my-special-class');

However, I have a <div> that is periodically updated with new content, and I need to keep reapplying the my-special-class to new elements that match the selector '#parent:has(#child)' inside that <div>.

How could one do that?

I am styling a third-party plugin so I don't have much control over its styling, events and so on.


Solution

  • One solution is to bind the DOMSubtreeModified event on the container div and add your code inside.

    $('.container').on("DOMSubtreeModified",function(){
        $('.parent:has(.child)').addClass('special-child');
    });
    

    // find elements
    var parent = $("#parent")
    var button = $("button")
    
    // handle click and add class
    button.on("click", function() {
      const el = '<div class="parent"><p class="child">Hello World</p></div>';
      parent.after(el);
    })
    
    $(function() {
      $('.parent:has(.child)').addClass('special-child');
    
      $('.continer').on("DOMSubtreeModified", function() {
        $('.parent:has(.child)').addClass('special-child');
      });
    
    })
    body {
      background: #20262E;
      padding: 20px;
      font-family: Helvetica;
    }
    
    .child {
      background: #fff;
      border-radius: 4px;
      padding: 10px;
      font-size: 25px;
      text-align: center;
      transition: all 0.2s;
      margin: 4px auto;
      width: 300px;
    }
    
    button {
      background: #0084ff;
      border: none;
      border-radius: 5px;
      padding: 8px 14px;
      font-size: 15px;
      color: #fff;
    }
    
    .special-child {
      color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <div class="continer">
      <div class="parent" id="parent">
        <p class="child">Hello World</p>
      </div>
    </div>
    <button>Add Child</button>