0

So, here's the problem...

I have to:

  1. Grab a page of html via a REST API with a AJAX call,
  2. Extract a table with a known id from that html (which, thankfully, is well-formed)
  3. Extract the associated css for the table from a style block,
  4. Append the table to a div on my page, and
  5. Re-apply the original CSS

Therefore the parts of the page that I'm interested in are:

<style>
 #tableid td.someclass {
  ...
  }
 #tableid td.anotherclass {
  ...
  }
 [etc etc ..]
</style>

And

<table id="tableid">
 ...
</table>

So, going through the list above 1,2 & 4 are no problem at all. It's 3 and 5 that are taxing the brain - there are no external stylesheets to worry about BTW, everything is in the page that I'm grabbing inside a single tag.

I guess I could extract the entire element and then append it to my page - but that is messy and could result in unwanted side-effects. What I'd like to do is just extract the styling that applies to #tableid and then apply them the table appended to my div.

Is there an elegant way to do that?

1 Answer 1

1

You could pull the styles from the header using a standard jQuery finder:

var styles = $('head style').text();

Then run a regular expression against it:

var tableID     = 'tableid',
    pattern     = new RegExp('#'+ tableID + '[^}]+}', 'g'),
    tableStyles = styles.match(pattern);

This should give you an array of styles for your table’s id. Now you can append these styles to your current document’s head:

$('<style/>', { text: tableStyles.join('\n') }).appendTo('head');

Your use case might require some fine–tuning, but this should approximately give you what you’re after.

Sign up to request clarification or add additional context in comments.

Comments

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.