0

I have multiple div like this

<div class="main">
<a href="/tohref.html">Category1</a>
<div class="cat_id">1111</div>
</div>

<div class="main">
<a href="/tohref.html">Category2</a>
<div class="cat_id">1222</div>
</div>

<div class="main">
<a href="/tohref.html">Category3</a>
<div class="cat_id">1333</div>
</div>

I want to get all a[href] text and div.cat_id text push into an array like this.

[["category1","1111"],["category2","1222"],["category3","13333"]]

2 Answers 2

2

Try this out:- http://jsfiddle.net/adiioo7/3rrpsvqs/2/

JS:-

var arr=[];
jQuery(function($){    
    $(".main").each(function(){
        var categoryName = $(this).find("a").text();
        var categoryValue = $(this).find(".cat_id").text();
        arr.push([categoryName,categoryValue]);
    });

    console.log(JSON.stringify(arr));
});

Log Output:-

[["Category1","1111"],["Category2","1222"],["Category3","1333"]] 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, This solution is working and easy to understand!
1

Try this fiddle: http://jsfiddle.net/o8qdv2Ls/2/

Code:

var my_array = new Array();   
var my_array1 = new Array(); 
$('div').each(function(){  
  my_array[''+$(this).attr('id')+''] = $(this).text();   
  my_array.push($(this).text());        
});
$('a').each(function(){
  my_array1[''+$(this).attr('id')+''] = $(this).text();
  my_array1.push($(this).text());
});

1 Comment

Hi, Your solution is also great! Thanks , but it didn't meet my criteria!

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.