thibaultlgd
thibaultlgd

Reputation: 65

Two different Div's have same ID and Class name which one is Work

I have a div with a specific ID like: id="1"

I have another div in a different section of the class such as: class="1".

I'm using the following jQuery to trigger my function, which should be really like onClick on ID div, action the other div which has the same ID has a class.

  $('#2').on('click', function(ev) {
      $(".video, .2")[0].src += "&autoplay=1";
      ev.preventDefault();
    });

Which works perfectly. However, I would like to make this function dynamic. How?

Upvotes: 0

Views: 232

Answers (2)

Sarah Groß
Sarah Groß

Reputation: 10879

You can just get the id of the clicked element with this.id and concatenate it to the selector string. I would also use attr("src", ...) in this case to prevent JS errors in case there is no matching element in the page (or check for this condition if you'd still prefer vanilla JS).

$('button[id]').on('click', function(ev) {
  var videoEl = $(".video ." + this.id);
  videoEl.attr("src", videoEl.attr("src") + "&autoplay=1");
  ev.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="video"><video class="2" src="video.mp4?"></video></div>

<button id="2">autoplay video</button>

Upvotes: 3

laruiss
laruiss

Reputation: 3816

$(document.body).on('click', 'HERE_A_SELECTOR_FOR_ALL_THE_ELEMENTS_WITH_IDn', function(ev) {
  $(".video ." + ev.target.id)[0].src += "&autoplay=1";
  ev.preventDefault();
});

Upvotes: 0

Related Questions