Home > Software design >  Appending additional selectors to a previously declared variable containing a DOM element
Appending additional selectors to a previously declared variable containing a DOM element

Time:05-27

I cannot for the life of me find a reference on this, yet it is seemingly a very awkward piece of code to beat. It may be due to the exact wording I was using to find a result, but as far as I can tell. This is impossible.

The question is simple, I have a radio DOM element and a variable set as a DOM element.

<fieldset >
    <input id="radio-1"  type="radio" name="mylittleradio" value="1">
    <label for="radio-1" >Radio 1</label>
    <input id="radio-2"  type="radio" name="mylittleradio" value="2">
    <label for="radio-2" >Radio 2</label>
</fieldset>


var domRadioInput = $('.my-little-radio input[type=radio]');

I then run some JS that essentially requires the checked status to be switched to a sibling radio input, the radio input I would like must have the value myNewValue.

domRadioInput   '[value="'   myNewValue   '"]'   .prop('checked', true);

I am aware the above is wrong, but do you know how it can be achieved?

Specific question: How can a variable set as a DOM element be reused to check for attribute changes, such as the value?

CodePudding user response:

I have a radio DOM element and a variable set as a DOM element.

What you have is a variable (domRadioInput) that refers to a jQuery object; that jQuery object has references to all of the DOM elements that matched the selector when you called $() (two elements, in your case).

I then run some JS that essentially requires the checked status to be switched to a sibling radio input, the radio input I would like must have the value myNewValue.

I'm going to assume that myNewValue contains "1" or "2". If so, you can use jQuery's filter (which is not the same as the one on arrays) to get a new jQuery object with all of the elements from your previous one that match the new selector (presumably just the one will match), then set the checked prop on them:

domRadioInput.filter(`[value="${myNewValue}"]`).prop("checked", true);

More in the jQuery API documentation.

  • Related