Evanss
Evanss

Reputation: 23583

Create an array not a variable of values taken from the dom with jQuery?

Im searching for elements with a class of 'some-class' within an element with a specific ID (provided by the variable myID).

For each one of these I need to get the value of the data attribute called 'data-att'. I then want to create an array of these but add the string custom-class-- to the beginning of each one.

My code below works except that it only generates 1 value. How can I make an array rather than a variable?

// a in the ID of the container to search in for elements with a class of 'some-class'
var myID = '#' + myID;

// Create a varialbe which starts 'custom-class--' and then has the data-att attribute
// of elements for elemts with a class of 'some-class'
var class = 'custom-class--' + $(myID).find('.some-class').attr('data-att');

UPDATE - here is a working codepen: http://codepen.io/anon/pen/reVeja?editors=1111

<a href="#" class="some-class" data-att="data-1">Link</a>

<div id="my-id">
  <a href="#" class="some-class" data-att="data-2">Link</a>
  <a href="#" class="some-class" data-att="data-3">Link</a>
</div>

<script type="text/javascript">

$(function() {

  // a in the ID of the container to search in for elemnts with a class of 'some-class'
  var myID = '#' + 'my-id';

  // Create a variable which starts 'custom-class--' and then has the data-att attribute 
  // of elements for elements with a class of 'some-class'
  var myClass = 'custom-class--' + $(myID).find('.some-class').attr('data-att');

  console.log(myClass);

});
</script>

Upvotes: 0

Views: 61

Answers (2)

Bj&#246;rn Grambow
Bj&#246;rn Grambow

Reputation: 368

You can use map() to loop through the elements and create automatically a new array filled with the values you return from the map callback. In the callback I am using data() to get the value of the data-att:

var parentId = '#PARENTID',
    clNames = $.map( $(parentId).find('.some-class'), function( i,el ){
        return 'custom-class--'+ $(el).data('att');
    });

But be aware that this one will always return a value, even if you don't have an data-att attribute on the element. If you have cases with no data-att you will end up with custom-class--undefined. Which is not really a problem, you could use it even as a default style.

Upvotes: 1

The Process
The Process

Reputation: 5953

You can try something like this:

var myID = '#' + myID;
var elemClass=[];

$(myID).find('.some-class').each(function(){
   if($(this).attr('data-att').length){ 

      elemClass.push('custom-class--'+ $(this).attr('data-att')) ;
   }

});

And note that you can't use reserved words like classin your code.

Upvotes: 4

Related Questions