0

How can I add an attribute into specific HTML tags in jQuery?( I dont want to overwrite )

I have it in HTML:

<td style="width: 30%">Hello</td>

style="width:30%" is important.

Now I'm using a function () and adding attr:

$(cell_above_old).attr('style', 'vertical-align : middle;text-align:center;');

But the style is overwritten:

<td style="vertical-align : middle;text-align:center;">

What I want is to add the line to the existing style.

<td style="width:30%;vertical-align : middle;text-align:center;">

There is some function to do this?, such as:

$().attr('addStyle','styles');
1
  • Personally I'd say to just create some css classes and then use addClass removeClass, because that doesn't overwrite other things. Commented May 16, 2018 at 17:12

2 Answers 2

2
$(cell_above_old).attr('style', 'vertical-align : middle;text-align:center;');

That is setting the entire attribute value. Change the css instead

$(cell_above_old).css({
    'verticalAlign': 'middle',
    'textAlign': 'center'
});

This will change just that css property in the style, leaving the rest alone.

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

Comments

1

This sort of thing is best done with classes. Add/remove classes with that styling as needed (via addClass, removeClass, and/or toggleClass).

But if you want to do it with an inline style, use css, not attr:

$(cell_above_old).css({
    verticalAlign: 'middle',
    textAlign: 'center'
});

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.