2

What would be the most efficient way to get the value 14500from the data-ls attribute below. I have never seen multiple properties for a single data attribute before, and I am looking for the faster way to extract the value and not have it depend on the order of the data attribute properties.

<div class="slide" data-ls="slidedelay:14500; transition2d: all;"></div>

.

var duration = $('.slide').data('ls').split(';');
duration = duration[0].split(':');
console.log("duration: " + duration[1]);

thanks

1
  • There isn't a way to access the data inside data-ls as an object that I know of. You may simply have to exact it from the sting "slidedelay:14500; transition2d: all;". Commented Aug 23, 2015 at 2:55

4 Answers 4

3

How about to do a loop on your split var then check the key if it's slidedelay to be sure.

e.g.

var duration = $('.slide').data('ls').split(';');
var slidedelay = "";
if(duration) {
    $.each( duration, function( key, value ) {
        val = value.split(':');
        if(val) {
          if(val[0] == "slidedelay") {
            slidedelay = val[1];
            return false;  // then break loop 
          }
        }
    });
}


console.log("duration: " + slidedelay);

Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1
var duration = $('slide').data('ls').match( /slidedelay *: *(.*?);/ )[1];

Regular expression visualization

Debuggex Demo

It returns the first matching string, so if you need it as a number, you need to use parseInt().

1 Comment

Thanks Laszlo..Not sure its faster than Robin's answer but I like the clean code.
0

Try this one:

<div class="slide" data-ls="slidedelay:14500; transition2d: all;"></div>

JS:

 var x = document.getElementsByTagName("div")[0].getAttribute("data-ls");
var x = x.split(":"); var val = x[1].split(';');
alert(val[0]);

JSFIDDLE https://jsfiddle.net/Grald/cgy5drL4/1/

1 Comment

I think you misunderstood the question. They want to get 14500.
0

Easy and quick way: JSnippet Demo

function getFrom(selector) {
    var val = null;
    var x = $(selector)[0]
             .getAttribute("data-ls")
             .split(' ')[0]
             .split(':');
    if (x.length > 1) val = parseInt(x[1]);
    return val;
}

$(function() {

    console.log(getFrom('.slide'));

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.