user957178
user957178

Reputation: 631

changing the color of the text using jquery

$(document).ready(function () {
            $("#btnhighlight").click(function () {
                alert("yes");
                var htext = $("#txthighlighttext").val();
                $("#lstCodelist option").each(function () {
                    var sp = $(this).text();
                    var sp1 = sp.split(' ');
                    $.each(sp1, function (i, l) {
                        if (l == htext) {
                            l.css('color', 'yellow');
                        }
                    });
                });
            });
        });

var x = "hello world"; I need to change the text color on l. that is suppor I got the text from the string "hello". css( Can I do l.('color', 'yellow'); I am getting javascript error.

if I do like this $(this).css('color', 'yellow'); Nothing happening.

thanks

Upvotes: 1

Views: 1942

Answers (4)

realshadow
realshadow

Reputation: 2585

As it was mentioned l is not a dom element, which means you just need to "push" it inside the next each loop.

$("#lstCodelist option").each(function () {
    var sp = this; //or $(this) and then you do sp.css('color', 'yellow');
    var sp1 = $(this).split(' ');

    $.each(sp1, function (i, l) {
       if (l == htext) {
           $(sp).css('color', 'yellow');
       }
    });
});

Upvotes: 0

Allen Liu
Allen Liu

Reputation: 4038

Try:

$(l).css('color', 'yellow');

Edit:

Ok...you are working with strings and not actual DOM elements. My suggestion is to dynamically place l into an element like <span> and apply the CSS to that and then replace the original text in the DOM. I actually did something similar to this a while back:

http://www.randomsnippets.com/2008/03/07/how-to-find-and-replace-text-dynamically-via-javascript/

I'm not saying this is the perfect solution but it will lead you down the right path.

Upvotes: 1

Zach Lysobey
Zach Lysobey

Reputation: 15714

will something like this work? (untested)

     $('<span>', {
            'style': 'color:yellow',
            html: l
        }).appendTo('#divName'); 

Upvotes: 0

Rafay
Rafay

Reputation: 31033

l in is the element you are iterating, wrap it inside the $ and you are good to go

try

$.each(sp1, function (i, l) {
if (l == htext) {
  $(l).css('color', 'yellow');
}

Upvotes: 0

Related Questions