0

I've a list of div

<div data-attr="sel" data-num="1"></div>
<div data-attr="notSel" data-num="2"></div>
<div data-attr="sel" data-num="3"></div>

I'm tryng to get a string only div with the data-attr="sel" set.

function SI_MoveTasks() {
    var getSelected = document.querySelector('[data-attr~="sel"]');
    var selectedNums = getSelected.dataset.num;
    alert(selectedNums);
}

Now i get (1), how can i get the concatenate string (1,3)? Thanks for support.

1
  • You have jquery tagged; are you planning to use it? Commented Jun 3, 2015 at 20:05

2 Answers 2

4

DEMO -> http://jsfiddle.net/0d54ethw/

Use querySelectorAll instead of querySelector since the latter only selects the first element as opposed to all of them.

Then use for loop as shown below

var getSelected = document.querySelectorAll('[data-attr~="sel"]');
var selectedNums = [];
for (var i = 0; i < getSelected.length; i++) {
    selectedNums.push(getSelected[i].dataset.num);
}

alert(selectedNums.join(','));
Sign up to request clarification or add additional context in comments.

Comments

1

You would need to use document.querySelectorAll to get all matching elements. document.querySelector returns only the first matching element, or null if there is none.

function SI_MoveTasks() {
    var getSelected = document.querySelectorAll('[data-attr~="sel"]');
    console.log(getSelected);
    var selectedNums = '(';
    for(var i=0; i< getSelected.length; i++) {
        if (selectedNums !== '(') {
          selectedNums += ',';
        }
      selectedNums += getSelected[i].dataset.num;
    }
    selectedNums += ')';
    alert(selectedNums);
}
SI_MoveTasks();

Thats a working code, jsFiddle is: https://jsfiddle.net/3kjye452/

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.