Let’s say I have this HTML:
<ul>
<li>
<a>Item one</a>
<small>#000000</small>
<span class="corner"></span>
</li>
<li>
<a>Item two</a>
<small>#ffffff</small>
<span class="corner"></span>
</li>
</ul>
I want to get the text between the span tag, and apply it as a background color to the ‘span’ inside the same ‘li’.
So what I tried is:
jQuery(document).ready(function ($) {
$("span.corner").addClass("custom-color"); //apply class custom-color to span
if ($("span.corner").hasClass("custom-color")) { //if the span.corner has custom-color class do the next
var cornerColor = $('.corner').prev('small').text(); //this should get the text between the 'small' tags
if (cornerColor !== '') { //if there is some text between 'small' tags, apply it as a css rule to the 'corner.span'
$('.corner').css('background-color', cornerColor);
}
}
});
Unfortunately it doesn’t work, it applies the ‘custom-color’ class but then it does not apply the css rule. If I replace the variable cornerColor to an actual color, it does. So I guess the error is in the variable to get the text inside the span. Any help would be much appreciated.
Thanks
When you do
var cornerColor = $('.corner').prev('small').text();you are taking a text of allsmalltags concatenated. So basicallycornerColor = "#000000#fffff"; which is obviously not valid.Code above uses .each to go through each small tag, takes it inner text and apply to
span.cornernext to it. Demo: http://jsfiddle.net/4Su4G/1/