When I tried to get an element close to the current node, this.clost("i") could not get it.

Asked 2 years ago, Updated 2 years ago, 69 views

HTML can be found as follows:

<div class="td">
  <i class="fa fa-hoge"></i>
  <div class="piyo">
    <span class="name">Tanaka Tanaka</span>
    <div class="radio">
      <div class="r-radio">
        <input id="radio-1" name="hogehoge" type="radio" value="true"/>
        <label for="radio-1">true</label>
      </div>
      <div class="r-radio">
        <input id="radio-2" name="hogehoge" type="radio" value="false"/>
        <label for="radio-2">false</label>
      </div>
    </div>
  </div>
</div>

Obtain the event that caught fire after pressing the radio button and

The contents of this are

<input id="radio-1" name="hogehoge" type="radio" value="true"/>

It is the node of .

I'd like to get <ic class="fa fa-hoge"></i> from this situation.

this.closeest("i") could not also be retrieved.
this.find("i") But it didn't work.

If you repeat this.parentElement, you can get it, but there is a readability problem, so I would like to avoid it if possible.

You might want to create a new selector, but
I have about 20 more td's left, so I would like to get the i from the current node.

I don't know how to implement it, so I'm in trouble.
Thank you for your cooperation.

javascript jquery

2022-09-30 21:21

1 Answers

In the HTML structure you provided, the i element is not the parent/ancestor element of the radio button, so you may not be able to retrieve it by repeating close or parentElement.

If you go back to the other tier parent element of the i element, you'll get to the common ancestor element of the i element and the radio button, so you might want to go back to the child element.

If $radio contains the jQuery element of the radio button, I think writing this code will be the desired behavior.

var$radio=$('input:radio[name=hogehoge]');//<- Actually `$(this)`?
var$i = $radio.clost('div.td') .children('i');
$i.text($radio.val();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div class="td">
  <i class="fa fa-hoge"></i>
  <div class="piyo">
    <span class="name">Tanaka Tanaka</span>
    <div class="radio">
      <div class="r-radio">
        <input id="radio-1" name="hogehoge" type="radio" value="true"/>
        <label for="radio-1">true</label>
      </div>
      <div class="r-radio">
        <input id="radio-2" name="hogehoge" type="radio" value="false"/>
        <label for="radio-2">false</label>
      </div>
    </div>
  </div>
</div>

There may be many other ways to write, and there may be better ways to do it, but I think I can do it with this.


2022-09-30 21:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.