user57082 user57082 - 3 months ago 10
Javascript Question

How can I add class for the link based on youtube.com/embed URL andress?

I have a lightbox plugin, which use lightview class for links.
So the usage looks like this:

<a href="https://youtube.com/embed/HPOcZtfjrrU?start=102&autoplay=1" class="lightview">Link for the site</a>


I want add this class (lightview) for everylink which started this url:


https://youtube.com/embed/


This is the important part:

I don't want to add class for links like that:

https://www.youtube.com/watch?v=XtSf8GqrF6Q

Because this url will be embedded on my site.

Answer

With jQuery you can select all the elements that have an attribute which start with a given value by using the [attribute^=value] selector. Then you would just need to add the lightview class to those elements. It is as simple as:

$("a[href^='https://youtube.com/embed']").addClass("lightview");

Here is a demo:

$("a[href^='https://youtube.com/embed']").addClass("blue");
a {
    display:block;
    color:red;
}

a.blue {
    color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a href="https://youtube.com/embed/HPOcZtfjrrU?start=102&autoplay=1">Video with right link</a>
<a href="https://www.youtube.com/watch?v=XtSf8GqrF6Q">Video without right link</a>
<a href="http://www.google.com">Link to Google</a>
<a href="https://youtube.com/embed/HPOcZtfjrrU?start=102&autoplay=1">Antoher video with right link</a>
<a href="http://stackoverflow.com">Another wrong link</a>