Home > Software engineering >  How can i get value of data-* jquery
How can i get value of data-* jquery

Time:03-19

<img src="lazy.png" data-kjkjsdfkjf="realurl.png">
<img src="lazy.png" data-3a4244454a="realurl.png">
<img src="lazy.png" data-32423fasf="realurl.png">
<img src="lazy.png" data-dasflkj="realurl.png">

how can i change every data-* to src?

    $("img").lazyload({
        one rror: function (element) {
            $(element).attr('src', jQuery(element).attr('data-*'));
        }
    });

CodePudding user response:

This works in vanilla JavaScript:

<img src="lazy.png" data-kjkjsdfkjf="realurl.png">
<img src="lazy.png" data-3a4244454a="realurl.png">
<img src="lazy.png" data-32423fasf="realurl.png">
<img src="lazy.png" data-dasflkj="realurl.png">

<script>
    // gets all images in document (you can do this with only a specific div instead of document if needed)
    let images = document.getElementsByTagName("img");

    // loops through images
    for(let i = 0; i < images.length; i  ){
        // the current image in the loop
        let image = images[i];

        // gets the name of the first property in the dataset
        let dataName = Object.keys(image.dataset)[0];

        // gets actual value in dataset from the name we found above
        let realUrl = image.dataset[dataName];

        // sets the new src
        image.src = realUrl;
    }
</script>

CodePudding user response:

Please try the following

const values = [];
document.querySelectorAll('img').forEach((img) => {
    const value = img.getAttributeNames()[1].split('-')[1];

    values.push(value);
});

console.log(values);
<img src="lazy.png" data-kjkjsdfkjf="realurl.png" />
<img src="lazy.png" data-3a4244454a="realurl.png" />
<img src="lazy.png" data-32423fasf="realurl.png" />
<img src="lazy.png" data-dasflkj="realurl.png" />

  • Related