1

Background:

I have a CMS tool that allows users to create a table inside the content area. If the option for a border is used, the tool sets the border attribute on the table, and does not use a style. My reset stylesheet defaults all tables to no border, and this overrides the table border attribute (i.e., no border is displayed).

As a quick hack, I put in some jQuery to grab table elements that have a non-0 border attribute and convert the border attribute into an inline style.

My question:

While I was able to get the code to work, it is not the solution I originally intended.

This is currently working:

    $("table[border!='0']").css('border', function() { 
         return $(this).attr('border') + "px solid"; 
    });

My original solution was to not require the function in the css method -

$("table[border!='0']").css('border', $(this).attr('border') + "px solid");

I realize as I write this question that $(this) doesn't refer to each item in the selection, as it does inside the function, thus my problem.

jsFiddle

Is there a way to accomplish this without the function?

2
  • The code you posted cannot work since .attr is a function so .attr['border'] is undefined. Commented Jul 10, 2012 at 11:34
  • Using a function as the second param to CSS looks to me like the correct and classy way of doing this. You can always split it up into multiple lines to avoid a function, but then since you are working with a collection of objects, that'll be a pain. In short, your current way is imo the best way. Commented Jul 10, 2012 at 11:38

1 Answer 1

1

No, using the function is the only (and best) way since otherwise you cannot access every item separately.

Note that your code contains a bug: $(this).attr['border'] should be $(this).attr('border') - otherwise you always get undefinedpx solid which doesn't make much sense.

However, as long as you don't have a ton of different values for border you could use CSS:

table[border=1] { border: 1px solid; }
table[border=2] { border: 2px solid; }

Obviously this would be messy with many different values but chances are good that you don't have many different border widths.

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

2 Comments

Thanks for the heads up on the typo - I had it correct on my site, just didn't retype it correctly.
I like the CSS approach - that's probably better, rather than running code on every page load.

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.