Patrick Witbrod
Patrick Witbrod

Reputation: 33

Select Div Title Text and Make Array With Jquery

I'm trying to add the text from all divs Title Attributes to an array but I can't seem to select the right thing.

I need the title because it will contain the string that I need to use.

Here are three divs with different titles

<div class = 'test' title='title1'>Hello</div>
<div class = 'test' title='title2'>goodbye</div>
<div class = 'test' title='title2'>goodbye</div>

Here is my Jquery so far.

$(document).ready(function() {

$array = $('[title][title!=]').each(function(){
  $(this).attr("title").makeArray;})

 alert($array)

});

The alert just says [Object object]

In my example I'm trying to select create an array that contains [Title1, Title2, Title3].

Can anyone help me do this?

********************************UPDATE************************************

Thanks the first one worked perfectly. I really appreciate it.

Upvotes: 3

Views: 1695

Answers (3)

adeneo
adeneo

Reputation: 318182

var array = $.map($('[title][title!=""]'), function(el) { return el.title });

FIDDLE

Selects all elements that has a title attribute that is not empty, and maps the titles to an array

Upvotes: 4

David Thomas
David Thomas

Reputation: 253318

I'd suggest:

var titles = $('.test').map(function(){
    return this.title;
}).get();

References:

Upvotes: 2

CRABOLO
CRABOLO

Reputation: 8793

var theArray = []; // set an empty array to a variable outside of scope

$('.test').each(function() { // loop through all the .test divs
    var theTitle = $(this).attr('title'); // selects the text of the title for the current .test element
    theArray.push(theTitle); // this adds the text of the current title to the array
});

console.log(theArray); // just to test and make sure it worked, remove once verify

Upvotes: 2

Related Questions