JQuery - get regexp value of data

I have html tags like this:

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

And I want to 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 am i doing this? thanks in advance

+5
source share
2 answers

You can use dataset to get a list of all the data-* attributes present in the element, and then data-* over them all.

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> 
+1
source

This is one of those situations when jQuery doesnโ€™t help you much. Probably the easiest way to skip the attributes that NamedNodeMap :

 var value; var attrs = $('.currItem')[0].attributes; for (var n = 0; n < attrs.length; ++n) { if (/^data-source.+$/.test(attrs[n].name)) { value = attrs[n].value; break; } } 

Example:

 $(".currItem").click(function() { var value = "(not found)"; var attrs = this.attributes; for (var n = 0; n < attrs.length; ++n) { if (/^data-source.+$/.test(attrs[n].name)) { value = attrs[n].value; break; } } alert("Value: " + value); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> Click a list item below: <ul> <li class="currItem" data-sourcemp3="http://**">xxxxx</li> <li class="currItem" data-sourcemp4="http://**">xxxxx</li> </ul> 

Or you can iterate over attributes many other ways , it's an object that looks like an array.

+1
source

Source: https://habr.com/ru/post/1247606/


All Articles