How can I add a css rule to a dynamically created element in jquery

Is it possible to add css to a specific dynamically created div in jquery? I want to add an overlay to a specific div but trying to find a way to pass the id from the dynamically created div to the jquery function in order to only add the CSS rule to that specific div, is becoming a task for me. When I click on the div it adds the overlay to all of them. Thanks for your time and here is my code.

foreach($selectedPhotoResult as $rowSelect){
    if($counter % 3 === 1){
        echo '</div><div class="row">';
    }
        echo'
        <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer">
            <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'"><div class="price" style="position:absolute;top:0px;;right:15px;z-index:98;height:50px;width:50px;border-radius: 0px 5px 0px 0px;background-image: linear-gradient(to bottom, rgba(0,0,0,0.8) 50%, rgba(0,0,0,0) 100%);"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div></a>
                <div class="well photoControlsMain pht-brd-cl">
                    <a class="mainImageProfile" style="display:block;" data-userMain-id="'.$row['ad_user'].'" data-pic-id="'.$row['ad_photo_thumb'].'">
                        <div class="imageOverlayStyle">
                            Something here
                        </div>
                        <figure>                                                        
                           <img src="'.$row['ad_photo_thumb'].'" class="img-responsive imageSizingGallery imageProfileStyleSmall" style="object-fit: contain;" width="100%" alt=""/>

                        <div class="photoControlsMainImage">
                            <p style="z-index:9999;">
                        <span class="text-prt-und-bl usernameIndexPos">'.ucwords($row['industryName']).'</span>
                        <span class="adRateIndexPos">$'.$row['ad_rate'].'/hr</span>
         ';

    if($userfile->member_is_loggedin()){    
        echo'<a class="userMsgID" data-toggle="modal" data-target="#msgUserModal" data-userSenduserID-id="'.$rowSelect['user_id'].'" data-userSend-id="'.$rowSelect['industryName'].'" data-username-modal="'.ucwords($rowSelect['industryName']).'"><span class="commentIcoPos"><i class="fa fa-comment-o"></i></span></a>';
            if($favList->rowCount() > 0){                                           
                foreach($favListResult as $rowFav){
                    if($rowFav['user_fav_id'] == $user_id){
                            echo'<span class="heartIcoPosRed adUnFav" data-unfav-id="'.$rowFav['fav_id'].'"><a><i class="fa fa-heart heartIcoRedColor"></i></a></span></a>';
                            }                                       
                    }   
            }else{
                echo'<span class="heartIcoPos adFav" data-userFav-id="'.$user_id.'" data-fav-id="'.$row['ad_id'].'"><a class="heartIcoWhite"><i class="fa fa-heart"></i></a></span></a>';
            }   
                echo city($row['ad_city']);
        }else{                                          
            echo'</a>
                <a class="loginDisplayHeader" style="display:none;"><span class="commentIcoPos"><i class="fa fa-comment-o"></i></span></a>
                <a class="loginDisplayHeaderFull" id="loginFormShowHeader"><span class="commentIcoPos"><i class="fa fa-comment-o"></i></span></a>
                <a class="loginDisplayHeader" style="display:none;"><span class="heartIcoPos heartIcoWhite"><i class="fa fa-heart"></i></span></a>
                <a class="loginDisplayHeaderFull" id="loginFormShowHeader"><span class="heartIcoPos heartIcoWhite"><i class="fa fa-heart"></i></span></a>
                ';

                echo city($row['ad_city']);
                }

            $likes = $conn->prepare("SELECT count(likes) as likeCount
                FROM 
                    likes
                WHERE
                    user_accept_id = :adUserId                                  
                ");
                $likes->bindParam(":adUserId", $adUserId);
                $likes->execute();
                $likesFetch = $likes->fetchAll();                                       
                if($likes->rowCount() > 0){
                    foreach($likesFetch as $rowLikes){

                        echo'<span class="userLikeBtnLG">'.thousandsCurrencyFormat($rowLikes['likeCount']).' Likes <i class="fa fa fa-thumbs-o-up thbsUPND"></i></span>';

                            }
                        }
                    echo'</p>
            </div>
        </figure>
    </div>
 </div>                                             
 '; 
}

Here is the jquery code so far

   $(".overlayPicHL").on("click", function() {
     const imageOverlayStyle = 
     $(this.nextElementSibling).find('.imageOverlayStyle');
     $(imageOverlayStyle).css({
     backgroundColor: 'yellow'
     });
   });

And this is the CSS for the overlay item

.imageOverlayStyle {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #008CBA;
  overflow: hidden;
  width: 100%;
  height: 0;
  transition: .5s ease;
}

It's a simple overlay transition, I just need to figure out how to add this overlay to a specific div that is pulled from the database...dynamically created. I have searched for a solution for a while now with no such luck yet.

The .imageOverlayStyle you want to target is a child of the next sibling of the clicked .overlayPicHL, so use nextElementSibling and [0]:

$(".overlayPicHL").on("click", function() {
  const imageOverlayStyle = $(this.nextElementSibling).find('.imageOverlayStyle');
  $(imageOverlayStyle).css({
    backgroundColor: 'yellow'
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer">
  <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'">overlayPicHL
    <div class="price"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div>
  </a>
  <div class="well photoControlsMain pht-brd-cl">
    <a class="mainImageProfile" style="display:block;" data-userMain-id="'.$row['ad_user'].'" data-pic-id="'.$row['ad_photo_thumb'].'">
      <div class="imageOverlayStyle">
        Something here
      </div>
      <figure>
        <img src="'.$row['ad_photo_thumb'].'" class="img-responsive imageSizingGallery imageProfileStyleSmall" style="object-fit: contain;" width="100%" alt="" />

        <div class="photoControlsMainImage">
          <p style="z-index:9999;">
            <span class="text-prt-und-bl usernameIndexPos">usernameIndexPos</span>
            <span class="adRateIndexPos">adrate</span>
          </p>
        </div>
      </figure>
    </a>
  </div>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer">
  <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'">overlayPicHL
    <div class="price"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div>
  </a>
  <div class="well photoControlsMain pht-brd-cl">
    <a class="mainImageProfile" style="display:block;" data-userMain-id="'.$row['ad_user'].'" data-pic-id="'.$row['ad_photo_thumb'].'">
      <div class="imageOverlayStyle">
        Something here
      </div>
      <figure>
        <img src="'.$row['ad_photo_thumb'].'" class="img-responsive imageSizingGallery imageProfileStyleSmall" style="object-fit: contain;" width="100%" alt="" />

        <div class="photoControlsMainImage">
          <p style="z-index:9999;">
            <span class="text-prt-und-bl usernameIndexPos">usernameIndexPos</span>
            <span class="adRateIndexPos">adrate</span>
          </p>
        </div>
      </figure>
    </a>
  </div>
</div>

jQuery CSS() for dynamically created elements, CSS At-rules CSS Properties CSS Animatable Properties CSS Color Values CSS Color How to bind click event to dynamically created HTML elements in jQuery the elements that are dynamically added to DOM using the jQuery click() method it will not work <p>Click the above button to dynamically add new list items. How to add CSS properties to an element dynamically using jQuery. Topic: JavaScript / jQuery Prev|Next. Answer: Use the jQuery css() method. You can use the jQuery css() method to add new CSS properties to an element or modify the existing properties values dynamically using jQuery.

Add the rules to a stylesheet so that they are automatically applied to the newly created elements. Chain the css() method when you create your elements: $('') . appendTo(document. ... Create a new stylesheet dynamically: $("").

$('<img id="newImage" src="text.jpg"/>')
.appendTo(document.body)
.css(style);

Create a new stylesheet dynamically:

$("<style>").text("#myNewEl { width:40px; height:35px; }").appendTo("head");

How to Bind Click Event to Dynamically Created Elements in jQuery, By calling element.style.color = "red"; you can apply the here will change all elements that the CSS rules apply to. How an end-user can create there form dynamically. If these questions ever came across your mind, then this article can help you. Prerequisite: Basic of HTML and CSS; Basic of JQuery; The plugin which we are going to use here is dform. The jQuery.dForm plugin generates HTML markup from JavaScript objects and JSON for HTML forms.

You can find class in entire document and add css, you can use next() if you want it to add to only next() div

$(document).on("click", ".overlayPicHL", function(){
    var id = $(this).attr("data-overlayPicID-id");
    $(this).next(".imageOverlayStyle").css({"height":"100%"}); //<-this is the css I want to add to the specific div when the icon has been clicked
});
.imageOverlayStyle {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #008CBA;
  overflow: hidden;
  width: 100%;
  height: 0;
  transition: .5s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'">

<div class="price" style="position:absolute;top:0px;;right:15px;z-index:98;height:50px;width:50px;border-radius: 0px 5px 0px 0px;background-image: linear-gradient(to bottom, rgba(0,0,0,0.8) 50%, rgba(0,0,0,0) 100%);"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div></a>
<div class="imageOverlayStyle" id="imgOvrlayID" data-imgOvly-id="'.$row['ad_id'].'">
    Something here
</div>

Dynamic style - manipulating CSS with JavaScript, (Please do not edit your post after you make it - make a new comment.) When you first posted, you had: $(clickedID).css({"background-color":� Adding New CSS Rule. Now lets add new CSS rules in dynamically added stylesheet above. In order to do that we first need to get the stylesheet in which we want to add new rule. var styles = document.stylesheets; The line above will get you all the stylesheets attached to the page which will return an array as:

Change css of Dynamically created element?, Attach Event to Dynamically Created Elements with jQuery In the script, attach click event on #lists li selector to change the background color of clicked <li> . $(this).css('background','#d9f531'); }); // Add new list item� jQuery css() Method. The following example will return the background-color value of the FIRST matched element: Use the css() method to add a pink background

Attach Event to Dynamically Created Elements with jQuery, This however does not rule out the possibility of such requirement. <html> < head> <title>Create Elements Dynamically using jQuery</title> <script var iCnt = 0; // CREATE A "DIV" ELEMENT AND DESIGN IT USING jQuery ".css()" CLASS. Updating an Existing CSS Rule. Very interestingly, updating a CSS rule at a paticular index is not possible. If you try to re-insert a new CSS rule at an occupied position, both the CSS rules will be updated in the DOM! So take care. So in order to update a CSS rule at a particular index, first delete the old rule and then insert the new rule.

Dynamically Add and Remove HTML elements using jQuery, Here's the javascript where I dynamically create the element In your html you link to ui/style.css , but the styling is in ui/profile.css jQuery library --> <script src ="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Latest The #rightcol rule in your CSS has no closing brace. Use element. If you want to add an element dynamically , use DOM in jQuery click() method (It will not work, because it binds the click event only to the elements Given an HTML document and the task is to change the style properties (CSS Properties) of an element dynamically with the help of JavaScript. Source for the HTML page - index.

Comments
  • use event delegation as $(document).on("click", "selector", function() {...});
  • appreciate the help @DevsiOdedra, I tried your way but for some reason it does not want to fire on my end. If I just use $(".imageOverlayStyle").css({"height":"100%"}); then it displays on all of them but if I use your $(this).next solution it does not fire the css rule
  • so try $(this).next().css.. it will work
  • Yeah for some reason this.next does not want to work. :( When I remove $(this).next and just have my original code $(".imageOverlayStyle").css({"height":"100%"}); then it fires the image overlay on all of the dynamic pics but when I use $(this).next nothing fires. :(
  • Thanks for the Solution @CertainPerformance, I tried your solution but it did not add the css rule. When I use $(".imageOverlayStyle").css({"height":"100%"}); it adds the style to all of the elements but when I added your code nothing would display. :(
  • The backgroundColor: yellow in the snippet is just an example to show that the code is working as desired. Of course, you have to change it to use the actual CSS you want there.
  • I tried to run your code using my css({"height":"100%"}) but still would not display the overlay. When I run my original code it adds the css but to all of the dynamicallly displayed images. Would there be some other reason why it will not add the css rule to that specific div?
  • Any console errors? As you can see by the live snippet, given the HTML provided in the question, the code in the answer appears to be working. If it doesn't work for you, it sounds like the HTML given in the question is not your actual HTML structure?
  • yeah I saw that your code was adding the proper styles when fired here in the code snippet, but when I ran it in my environment, it would not fire the css rule and display the overlay on any of the divs. I updated my code with some more of what I am working with around that overlay. thanks
  • @Stuckfornow can you post you html where having multiple blogs and divs
  • I added some more of the code to give you a little more insight into what might be going on. Thanks for your time.
  • yes but it incomplete, just add complete div like start <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer"> and upto end of that div