Nitish kumar thakur
Nitish kumar thakur

Reputation: 55

setting color of a link in javascript

I want to set the color of "val" in the link in below code.

var link = $('<a href="#" class="album">' + val + '</a><br><br>');//this is the link
link.style.color="red";//this is how iam trying to set the color of "val"

SO HOW TO EXACTLY DO IT.

Upvotes: 0

Views: 137

Answers (5)

Lajos Arpad
Lajos Arpad

Reputation: 76426

link.css("color", "red")

However, I think it would be better to create a css class for that and set up the color there. In Javascript/jQuery I would just add the class to the tag when needed. It is more elegant.

Upvotes: 0

Scalpweb
Scalpweb

Reputation: 1971

You can do this:

link.css({ color: 'red' });

But the correct and nice way would be:

$(".parent_element").prepend('<a href="#" class="album">'+val+'</a><br><br>');
$(".parent_element > a:first").css({ color: 'red' });

Upvotes: 1

Quentin
Quentin

Reputation: 943163

You could use link.style.color="red" if link was an HTMLElementNode, but it isn't. It might be a jQuery object, but if you are using an older version of the library then it will return undefined.

First you need to fix your jQuery call. You can't create multiple elements at the top level. (You can skip this bit if you are using a sufficiently new version of jQuery).

Since there is no good reason to use a double <br> (it shouts "Use CSS to add a margin instead"), I've taken them out:

var link = $('<a href="#" class="album">' + val + '</a>');

Now you have a jQuery object so you can either use the jQuery method of setting CSS:

link.css("color", "red");

or get the HTMLElementNode from the jQuery object and use that:

link.get(0).style.color="red";

Upvotes: 0

Abijeet Patro
Abijeet Patro

Reputation: 2884

If you are using jQuery(which it does seem like) go ahead with this,

jQuery

link.css("color","red");

Otherwise, JavaScript

link[0].style.color = "red";

What you did doesn't work because link is an array. Before applying a style to it, you have to first select the first element by link[0] and then operate on it.

Upvotes: 0

kamituel
kamituel

Reputation: 35950

Try this:

$(link[0]).css({ color: 'red'});

The reason for this is that link is not an <a> element - it's a set of elements: <a>, <br> and another <br>.

Another approach would be:

link.css({ color: 'red' });

but this will set this CSS to not only <a>, but both <br>'s as well (not a big deal though).

Upvotes: 0

Related Questions