Marc
Marc

Reputation: 9537

JQuery - How to use a variable as selector using an attribute with it?

What I would like is to do this:

var theId = anId;

$('#someId .someClass[id=' + theId + ']').css('border-color', 'red');

...but using a varible for the "selector part":

var mySelector;

if(condition1){mySelector= $('#someId .someClass');}
if(condition2){mySelector= $('#anotherId .anotherClass');}

$.each(anArray, function(i, v) {
    mySelector[id=' + v.id + '].css('border-color', 'red'); 
});

(This is unfortunately not working. I need help for correcting this syntax)

I tried several syntax that did not work. Hope someone can help. Thank you in advance for your replies. Cheers. Marc.

Upvotes: 1

Views: 239

Answers (4)

Álvaro González
Álvaro González

Reputation: 146450

I think there're a couple of misused terms in your question. Learning them will probably help you to fix your code.

jQuery object instance: it's a JavaScript object that (among other things) contains a possibly empty internal array of DOM nodes on which you can perform further operations. You obtain one every time you call jQuery() (possibly aliased as $()).

Selector: It's a JavaScript string that represents a CSS query rule, e.g.: "ul>li:first". Many functions in jQuery, including the jQuery() function, accept selectors as parameters and use them to find or filter DOM nodes in the current chain.

So you basically have strings and objects and both are regular JavaScript data types and behave as such. You can, for instance, store them in variables or pass them as function arguments. You just need to know the difference between a CSS selector and the HTML elements found through it.

Upvotes: 0

Matteo-SoftNet
Matteo-SoftNet

Reputation: 531

After your edit, I think you should do this:

var mySelector_string;
var theId = anId;

if(condition1){mySelector_string= '#someId .someClass';}
if(condition2){mySelector_string= '#anotherId .anotherClass';}

$.each(anArray, function(i, v) {
    $(mySelector_string+"[id='" + v.id + "']").css('border-color', 'red'); 
});

Upvotes: 1

csharpnumpty
csharpnumpty

Reputation: 3723

If your question is how you can cache a selector which is dynamically constructed for re-use, then you can do the following:

$("div p a " + someOtherSelectorRequirement).click(function(){ });

can become

var a = $("div p a " + someOtherSelectorRequirement);
a.each(function(){ Console.Log($(this).text());
a.addClass("someClass");

if you are asking if you can re-use the same selector in an object, or variable.

Upvotes: 0

Mild Fuzz
Mild Fuzz

Reputation: 30691

$('#someId .someClass #'+theId).css('border-color', 'red');

will get a child of .someClass with id theId

$('#someId .someClass#'+theId).css('border-color', 'red');

will get an instance of .someClass with id theId

Upvotes: 0

Related Questions