I am stuck in a situation where I have a container with a single line of text, perfectly centered. Occasionally, the text is longer, and it breaks onto a second line. This throws off the layout, so I need a solution. I am thinking of using jquery to say, “if the number of characters goes above 28 characters, then apply a margin-top of -10px to center the text.”
How would you go about this in jquery? That is, creating a conditional statement that applies rules based on the number of characters? Here is my html, the span class of redstrip needs a margin-top of -10 if the number of characters goes above 28 characters:
<a href="#">
<img src="images/dummy3.jpg" alt="dummy">
<span class="redStrip">Here is a bunch of dummy text that is a bit too long</span>
</a>
While Anthony’s answer is spot on, it’ll only work for singular elements because of the behavior of
.text()on jQuery wrapped sets with multiple elements. (i.e. if.redstripselected more than one DOM element, a simpleifwouldn’t cut it).Expanding on his answer, you may want to apply a callback filter, or an
.each().