简体   繁体   中英

Add class to element with dynamically added data attribute

Ok, so I have a HTML file, that looks something like this:

while($stuff = $junk->fetch()){ ?>
    <div class="top-div" data-place-id="<?php echo $place['id']; ?>"></div>
    <div>
        <article>
            <div>
                //some stuff
            </div>
            <div>
                <span class="expand" data-place-id="<?php echo $place['id']; ?>"></span>
            </div>
        </article>
    </div>
} ?>

As you can see, for each result from a database, a structure like this is being output. Naturally, there are going to be at least a few of these each time. I wish to make it so, that each time the span is clicked, a class is added to the <div data-place-id=""> where the data-place-id is the same as the clicked elements.

I tried doing it this way:

expandOverlay = function(){
    $(".expand").each(function(){
        $(".top-div").addClass('is-expanded');
    })
})

But, this just adds the class to every single element with this class. Then I tried this:

expandOverlay = function(){
    $(".expand").each('click', function(){
        var dataAttr = $(this).data();
        if($(".place-overlay").data() == dataAttr){
             $(this).addClass("is-expanded);
        }
    })
});

But that didn't work either.

So, how do I get the .data() from my clicked element and how do I find other elements with the same data attribute, so I can assign it a class?

$('span.expand').click(function() {
    $('div[data-place-id="' + $(this).data('place-id') + '"]').addClass('is-expanded');
});

Cristian has it right, but it may not need to be that complex. How about this?

$('span.expand').click(function() {
    $(this).closest('div[data-place-id]').addClass('is-expanded');
});

Doesn't much matter what the data-place-id value is, does it?

try this,

   $('.expand').click(function(){

  dataid = $(this).data('place-id');
   $('div[data-place-id="'+dataid+'"]').addClass('is-expanded');
   })
  • First grab the data attribute of clicked item
  • Mave a div selection where data-place-id is same as span's data-place id ny concatenating the attribute selector.

this works?

$('span.expand').click(function() {
    $(this).closest('div.top-div').addClass('is-expanded');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM