Link to home
Start Free TrialLog in
Avatar of becraig
becraigFlag for United States of America

asked on

Javascript iterating through html dump

I need to query an html dump using javascript and find all matches for a specific text and create a div with that information.

I seem to be really stuck on how to even start.

I want to be able to loop thru and create a div based on the values:
e.g <div style="height:(whatever the first height value is from the loop")><a href = (product id from first loop)>click here</a>


Attaching the html dump


   
 <div class="div class">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>List #</th>
                    <th>Product </th>
                    <th>Description</th>
                    <th>Price</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <tr style="height: 50px;">
                    <td>1</td>
                    <td>TD Info</td>
                    <td>TD Info2</td>
                    <td>1</td>
                    <td><a href="/products/detail?id=1">cick here</a></td>
                </tr>
                <tr style="height: 52px;">
                    <td>2</td>
                    <td>TD Info</td>
                    <td>TD Info2</td>
                    <td>9</td>
                    <td><a href="/products/detail?id=12">cick here</a></td>
                </tr>
            </tbody>
        </table>
    </div>

Open in new window

Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

If you're happy using jQuery, then it should be fairly straight forward.

This code assumes your HTML dump is stored in a variable called html. It will loop through the <tr> elements and create a new div for each one it finds, and then inject them into an element with an ID of response

$('tbody tr', $(html)).each (function() {
    $('#response').append(
        $('<div>')
            .attr('style', $(this).attr('style'))
            .append($('a', this))
    );
});

Open in new window

Avatar of becraig

ASKER

Works perfectly and I have one other question - closely related.

I have an array that is dumped to me with two values

I want to be able to iterate through this array and do something similar
Array [ 50, "\n  <td>81</td>\n            <td><a href=\"/products/detail?id=1\">Click here</a></td>\n        " ]

Open in new window


Strip out the first element "50" and then "id=1"

So I can create <div style="height:50;"><a href ='id=1'>click here</a></div>
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial