开发者

jquery .css a:link of a jquery object

开发者 https://www.devze.com 2023-04-03 03:00 出处:网络
I want to use the jQuery.css() property to color property of a link. The straightforward way would be to use

I want to use the jQuery.css() property to color property of a link. The straightforward way would be to use

var $el = $("#test a:link"); //don't want to use this
$el.css({"color"  : "red"});

but I already have $el defined and used in multiple other places as

var $el = $("#test"); 

Can I still access the a:link a:visited a:hover a:active properties by reusing $el combined wit开发者_如何学运维h some other code?

($el/*other code to access a:link of #test*/)
.css({"color"  : "red"});

http://jsfiddle.net/RUYfZ/1/ Thanks.


jQuery takes an optional 'context' parameter allowing you to search inside an existing result:

var $el = $("#test"); 
$('a:link', $el).css({"color"  : "red"});

The context can be a DOM element, document, or jQuery object.


If all you are doing to $el is assigning css properties, you don't even need to use the variable. Try the following

$('#test a:link').css('color', 'red')

Or, if $el is currently defined as #test (it points to the element with the id test), you can do

$('a:link', $el).css('color', 'red')


$el.find('a:link').css('color', 'red');


edit: applied this solution to your jsfiddle: http://jsfiddle.net/RUYfZ/3/

Also, not sure what you mean by using the :visited, :hover, :active pseudo-selectors. jQuery selectors are used for querying the DOM, not for state-dependent styling. Even in CSS, those pseudo-selectors all select the same DOM nodes, they just apply different styles depending on the state.


If $el is in scope in the location you wish to use it, it can be reused. If $el is out of scope, you will need to assign it again.


Use jQuery's .children() selector method, where you give jQuery a selector to operate on the children of the given parent element, as such: $el.children('a:link')

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号