views:

5772

answers:

2

How would I perform the following in JQuery?

var elmOperator = document.getElementById(elm.id.replace('Include', 'Operator'));

The ID that is being manipulated would look something like Criteria[0].Include. I am trying to create a variable for a related ID which is Criteria[0].Operator.

Thanks in advance!

+1  A: 

Assuming elm is a jQuery object, not a DOM object, you could do this:

var elmOperator = $("#" + elm.attr('id').replace('Include', 'Operator'));

If it is a DOM object, you can do this (which would be a tiny bit faster):

var elmOperator = $("#" + elm.id.replace('Include', 'Operator'));

The bigger question is why you'd want to do this. If you don't know something as basic as the jQuery selectors and attr(), is your page using jQuery at all anywhere?

Plutor
in your second example, if you already had a DOM element, i wouldn't convert it to a jQuery object. it's a lot more overhead and more typing to boot. Compare: "$(elm).attr('id')" to "elm.id"
nickf
A: 

You can still use old javascript in jQuery so for your sample it would be something like this:

var operators = $('[id*=Include]').map(function() {
    return $('#' + $(this).get(0).id.replace('Include', 'Operator'));
});
operators.css('background', 'red');

In this sample we are selecting all the Include elements and then performing a 1:1 mapping of the elements to a new array of operator elements, finally we are setting all the operators background to red.

bendewey