0
votes

This is a bit of an unusual question, but is it possible in javascript to change text styles for every other line? Let me be a bit more specific. Assume I have a page with several paragraphs. What I want to do is alternate text styles (font color or background color) for each line, as they appear on my screen.

Here's the idea. I'd like to make a browser extension that automatically colors every other line in a paragraph to make it easier for readers to follow along with what they are reading on a page. Thoughts? If it's possible, how should I go about writing this?

2
Styles are applied to elements, not "lines". You could try to wrap lines of text in <span> elements or something, but that would be pretty complicated and obviously would fail if the window size changed. You could put your text in a <table>, that would be simpler.Pointy
It would be complicated. You can't style the nth line of text in a paragraph directly. You'd have to use javascript to calculate the height of each line of text, factoring in font size and line height, then create a repeating striped background on the paragraph with the appropriate dimensions.Sean

2 Answers

0
votes

If you knew the line height you could create a repeating background gradient to match. (And you could figure out the line-height with javascript if you had to.)

p {
  --spacing: 1.5rem;
  line-height: var(--spacing);
  background-image: repeating-linear-gradient(transparent 0 var(--spacing), skyblue var(--spacing) calc(var(--spacing) * 2));
}
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
0
votes

It is absolutely possible to do that using javascript instead of using css. I think what your question means it to change the paragraph (html tag), not to change every lines because it is much complicated to change the lines instead of changing the style of html tag.

html:

//I use `<h1>` as an example, but of course you could use <p>, <span> or other tag.
<h1 id = 'h1'></h1>

Example using css:

h1{
background:black;
color:white;
}

Example using javascript:

document.getElementById('h1').style.color = 'white';
document.getElementById('h1).style.background = 'black';