split("\n"), , , <span> , , join("<br/>") .
var lines = document.querySelector("p").innerHTML.split("\n");
for(var key in lines)
lines[key] = "<span class='first-letter'>" + lines[key].substr(0, 1) + "</span>" + lines[key].substr(1);
document.querySelector("p").innerHTML = lines.join("<br/>");
span.first-letter {
font-weight: bold;
color: red;
}
<p>This is a line
This is another line
This is yet another line</p>
Hide result( )
Another option is split("\n"), as before, but actually replace each line with yourself, enclosed in a tag <p>. Then join()line and replace the original parent with the lines themselves. This allows you to use the ::first-letterCSS pseudo-element for the styles of these classes and is more semantically correct than the previous one.
var lines = document.querySelector("p").innerHTML.split("\n");
for(var key in lines)
lines[key] = "<p>" + lines[key] + "</p>";
document.querySelector("p").outerHTML = lines.join("");
p::first-letter {
font-weight: bold;
color: red;
}
p + p {
margin-top: -16px;
}
<p>This is a line
This is another line
This is yet another line</p>
Run codeHide result source
share