nickcoxdotme
nickcoxdotme

Reputation: 6707

jQuery: loop through elements and wrap in different tag

I'm scraping content off of a public domain site (cancer.gov), and I want to reformat the markup because it's terribly formatted in a table. I have jQuery at my disposal, and I'm just trying to put it into the console so I can copy it and paste it into Vim.

I've gotten as far as making an array of the td elements I want to make into h3's, but when I try to loop over them and wrap them in h3 tags, I get Error: NOT_FOUND_ERR: DOM Exception 8, which I believe is that a DOM element isn't found, which makes no sense.

Check out my commented fiddle.

Bonus points: The td's are all questions, and the only way I could think of to split them into array indices was to split them on the ?, which cut out the question mark in the output. What's the best way to put them back in?

Update

If you want to check out the page and try things in the console, it's here.

Upvotes: 1

Views: 362

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34196

You could simply grab the content into an array and then do whatever you want with the array without the worry of the question mark.

var myarr = $('#Table1').find('tr:even');//even to exclude the hr rows

here I show some things you can do with that:

var myQuest = myarr.find('td:eq(0)').map(function () {
    return $(this).html();
});//questions
var myAns = myarr.find('td:eq(1)').map(function () {
    return $(this).html();
});// answers

//process the arrays:
for (var i = 0; i < myQuest.length; i++) {
    alert(myQuest[i]+ myAns[i]);
};

myarr.find('td:eq(0)').wrap('<h3>');//wrap the questions

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 220026

Creating a jQuery object does not magically turn them into DOM elements.


Just create on big string of HTML, and pass that to the jQuery constructor:

var questions = $('selector here...').text().split('?');

questions = $('<h3>' + questions.join('?</h3><h3>') + '?<h3>' );

Here's your fiddle: http://jsfiddle.net/M4Pn5/1/

Upvotes: 1

Related Questions