skip to Main Content

Im trying to find the value of the first <p> tag inside my div when i click a button inside the same div.
Note: The $(this) doesn’t seem to work.

Here’s my code:

<div className="cartcontainer">
  <p
    key={item.id}
    style={{
      display: "inline-block",
      marginTop: "auto",
      marginBottom: "auto",
      float: "left",
    }}
  >
    NFT ID: {item.id}
  </p>
  <p
    key={item.id}
    style={{
      display: "inline-block",
      marginTop: "auto",
      marginBottom: "auto",
      float: "left",
    }}
  >
    Price: {item.price}
  </p>
  <button
    style={{
      float: "right",
      width: 40,
      height: 40,
      fontSize: 20,
      borderRadius: 12,
      display: "block",
    }}
    onClick={() => removeCartItemHandler(cart.findIndex($(this).closest("p")))}
  >
    X
  </button>
</div>

3

Answers


  1. simple one-liner, self-explanitory:

    $( ".cartcontainer p:first-child" ).text();
    
    Login or Signup to reply.
  2. jQuery has no place within a React project. The former operates on the DOM directly whereas the latter uses state to drive the display.

    Instead of trying to access a known value from a previous element, just use the known value

    <button
      type="button"
      style={{
        float: "right",
        width: 40,
        height: 40,
        fontSize: 20,
        borderRadius: 12,
        display: "block",
      }}
      onClick={() => removeCartItemHandler(cart.findIndex(`NFT ID: ${item.id}`))}
    >
      X
    </button>
    
    Login or Signup to reply.
  3. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div className="cartcontainer">
      <p>
        NFT ID: 1
      </p>
      <p>
        Price: 23
      </p>
      <button
        onclick="removeCartItemHandler(this)"
      >
        X
      </button>
    </div>
    <script>
      function removeCartItemHandler(e){
        console.log($(e).siblings("p")[0]);
      }
    </script>

    JQuery has a method called siblings where you can find all the nodes associated with the same parent class. You can pass class name, id, and selector to fetch a particular element. as it returns an array, you can fetch the first element via indexing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search