1

Given HTML such

<span class="L5" letters="a"></span>
<span class="L5" letters="b"></span>
<span class="L5" letters="c"></span>
<span class="L5" letters="d"></span>
<span class="L5" letters="e"></span>

How to return an array : var list = [ 'a','b','c','d','e' ];

I tried $(".L5").attr("letters"); without success (jsfiddle).

3 Answers 3

2

You need to get the array of elements with that class type then push their attribute letters value into a new array.

let list= [];
let spanElements = $('.L5');

for(let x =0; x < spanElements.length; x++){
    list.push($(spanElements[x]).attr('letters'));
}
Sign up to request clarification or add additional context in comments.

Comments

1

Ryan's answer will definitely do the job with jQuery. However, and I'm not sure how many elements you are going to be parsing in this way, if performance matters you can accomplish the same thing without jQuery by using Array.from() and map()

var list = Array.from(document.getElementsByClassName('L5')).map(function (element) {
    return element.attributes.letters.nodeValue
});

Fiddle with console.time()

Comments

1

You could use jQuery.map() combined with jQuery.attr()

Code:

const list = $('.L5').map((index, elem) => $(elem).attr('letters')).get();

console.log(list);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="L5" letters="a"></span>
<span class="L5" letters="b"></span>
<span class="L5" letters="c"></span>
<span class="L5" letters="d"></span>
<span class="L5" letters="e"></span>

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.