Can I add a style tag to innerHTML?
Asked Answered
D

2

11

I'm trying to post an innerHTML table. Would like the font size in one cell to be bigger. Is it possible to include a style tag like so?

cell4.innerHTML = "<style: font-size:40px>" + "John Doe" + "</style>" +  "</br>";

I tried the following fiddle, but it isn't working. http://jsfiddle.net/s1dj3x8e/

Duntson answered 12/11, 2014 at 15:34 Comment(2)
@Billy It does not show any research effort; it is not usefulHemline
research? effort? didnt I try the style font-size and only missing the word 'div' from the the correct answer?Duntson
M
15

The <style> tag is meant to be a container for CSS code inside the head, so what you're trying to accomplish cannot be done with that element in this context.

Try replacing the following line:

cell4.innerHTML = "<style: font-size:40px>" + "John Doe" + "</style>" +  "</br>";

With:

cell4.innerHTML = "<span style='font-size:40px'>John Doe</span>";

Updated fiddle (now with span instead of div as correctly pointed out by Zach below):

http://jsfiddle.net/jbhw1qf0/

Mccord answered 12/11, 2014 at 15:40 Comment(7)
You shouldn't use divs for styling a section of text. Also I'm curious why you have " + "Hemline
@ZachSaucier I picked up on that as soon as I got your comment. Was minimizing the original code and simply never saw the pointless concatenation. Curious, what's wrong with divs being used to style a section? Span I typically would use inside, for example, a sentence to grab a word. But this context is the entire cell.Mccord
@DrewKennedy It's just syntactically incorrect for the same reasons why you'd use spans in a text section. That's what they're made forHemline
@ZachSaucier Fair enough. You learn something new every day, even little things like this. I'll make the change in my answer.Mccord
@DrewKennedy So then it's the same answer as the one I suggested :PHemline
But the meat of the answer is the same. Implementing the change suggested is easy to do and is not required in an answerHemline
Style tags don't have to be in the headHemline
H
4

Style tags are meant to contain CSS blocks including selectors, allowing them to style multiple elements at a time. All of the CSS for the style tag should go between the <style> tags themselves.

To do what you're trying to do, you need to return an element that either uses a class that has defined styles or inline styles like so:

cell4.innerHTML = '<span style="font-size:40px">John Doe</span>';

OR

cell4.innerHTML = '<span class="fs40">John Doe</span>';

where the CSS .fs40 { font-size:40px; } in your stylesheet.

Hemline answered 12/11, 2014 at 15:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.