Search code examples
javascriptattributesclone

Clone a part of an attributes value to another attribute in another element - js


I want to [Title] This is my wanton code:

<script>
$(document).ready(function(){
    var thmbElt = document.getElementsByClassName("imgbox")[0]{var vl1 = $(this).attr("src");};
    $(.h_iframe-aparat_embed_frame).attr("src",function{
        return "https://www.example.com/video/video/embed/videohash/"+vl1.substr(51, 56)+"/vt/frame"; 
});
</script>

Thats result is: nothing


Solution

  • If I understand correctly, you want to get src of one element and use part of it in another element. The below is the sample:

    <img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?h=350&auto=compress&cs=tinysrgb" 
    class="imgbox" width="80px" height="80px" />
    <img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?h=350&auto=compress&cs=tinysrgb" 
    class="imgbox" width="80px" height="80px" />
    
    <script>
       $(document).ready(function(){
            var thmbElt = document.getElementsByClassName("imgbox")[0];
            var thmbElt1 = document.getElementsByClassName("imgbox")[1]; //Change this line to get img src from another field
    
            var attr = thmbElt1.getAttribute("src"); 
            var attrSubset = "https://www.example.com/video/video/embed/videohash/" + attr.substr(8,6) + "/vt/frame";
            thmbElt.setAttribute("src", attrSubset);
        });  
    </script>