Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - get data value with regex

Tags:

jquery

regex

I have html tags like this:

<il class="currItem" data-sourcemp3="http://**">
<il class="currItem" data-sourcemp4="http://**">

And i want get this data value, Even if this mp3 or mp4 I wrote:

var A = $('.currItem').attr("data-source(.+)")
console.log(A);

Or:

var srcName = new RegExp(/data-source.+/g);
var A = $('.currItem').attr(srcName)
console.log(A);

And i get "undefined"

How i do it? Thanks in advance

like image 977
ABE Avatar asked Oct 30 '22 05:10

ABE


1 Answers

You can use dataset to get the list of all the data-* attributes present on an element and then iterate over all of them.

Demo

// Select all the elements having the class
var allEl = document.querySelectorAll('.currItem');

// Regex for data attribute
var regex = /^sourcemp\d+$/;

// Iterate over all the elements
for (var i = 0; i < allEl.length; i++) {
    // Get the list of all available data-* attributes on current item
    var data = Object.keys(allEl[i].dataset);

    // Iterate over the all data-* attributes
    for (var j = 0; j < data.length; j++) {
        // Check if this is the data attribute we're interested in
        if (regex.test(data[j])) {
            // Get value of the it
            var value = allEl[i].getAttribute('data-' + data[j]);
            console.log(value);
        }
    }
}

var allEl = document.querySelectorAll('.currItem');
var regex = /^sourcemp\d+$/;

for (var i = 0; i < allEl.length; i++) {
    var data = Object.keys(allEl[i].dataset);
    for (var j = 0; j < data.length; j++) {
        if (regex.test(data[j])) {
            var value = allEl[i].getAttribute('data-' + data[j]);
            console.log(value);
          
            // For Demo
            document.body.innerHTML += '<br />Data attribute = ' + data[j] + ' value = ' + value;
        }

    }
}
<il class="currItem" data-sourcemp3="http://**"></il>
<il class="currItem" data-sourcemp4="http://Test.this"></il>
like image 58
Tushar Avatar answered Nov 08 '22 03:11

Tushar