Add text and YT Video ID to specific div of embedded video using jquery/javascript

Viewed 15

I'm using a Learning Management System (LMS) where users can add YouTube videos. With the help of the Stack Overflow community, I devised the following jquery code to make the YouTube embed responsively and also wrapped in a video wrapper (for aesthetic purposes):

$('iframe[src*="youtube"]').each(function() {
    $(this)
      .wrap('<div class="video-wrapper rounded shadow mt-5 mb-5"></div>')
      .after('<div class="video-text"></div>')
      .wrap('<div class="embed-responsive embed-responsive-16by9"></div>');  
});

In the LMS YouTube videos are presented like this now: YouTube embed in LMS

As you can see from the code, there's also a with the class "video-text". Here I want to place some HTML: <p>Direct link: <a href="https://www.youtu.be/+ videoID>Video Title</a></p>

I used the append function

$( ".video-text" ).after("<p>Direct Link: </p>" );

to add some text in a p tag. This works fine, however it appends it to all divs with the class "video-text". Not only to the one of the just embedded video. It looks like this now in the LMS: YouTube embed with some text in the div with class"video-text"

I have two questions

  1. How can I add specific HTML to only the of the YouTube video I just embedded?
  2. How can I add an a tag to the div with class"video-text", which reads href="https://www.youtu.be/+VideoID to the YouTube video I just embedded

For the latter question, which seems way more complex to me, I discovered you can use javascript to extract the YouTube video ID using a regular expression:

function getId(url) {
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
    var match = url.match(regExp);

    if (match && match[2].length == 11) {
        return match[2];
    } else {
        return 'error';
    }
}

As I'm a newbie, I have no idea how this code looks like in jquery. I guess, I have several pieces of the puzzle to get it working, but at the moment I can't seem to put them together in one coherent piece of code.

Does anyone have pointers to get me into the right direction?

0 Answers
Related