Is there a way for me to choose the ID and retrieve its value from the input data within this particular row?

Here is what I am trying to accomplish.

When the modify button is clicked, I want the div with role 'ucomment' to transform into an input form with its original value pre-filled.

However, I am having trouble selecting the specific div.

I attempted to use the following code to target the desired element, but it did not work as expected.

$(this).closest("div[role='ucomment']")

How can I correctly select the div in this situation?

<ul id="comments" class="list-group">
<script id="commentTemplate" type="text/x-handlebars-template">
    {{#each list}}
      <li class="list-group-item d-flex justify-content-between align-items-center">
          <div class="row w-100">
            <div class="col-2" name="uid">{{uid}}</div>
            <div class="col-8" role="ucomment" name="ucomment">{{ucomment}}</div>
            <div class="col-2" name="regdate">{{prettifyDate regdate}}</div>
          </div>
            <button type="button" class="btn" onclick="modifyComment()">Modify</button> 
            <button type="button" class="btn" onclick="deleteComment()">Delete</button> 
        <span class="badge badge-primary badge-pill">14</span>
      </li>
    {{/each }}
</script>
</ul>
        <button id="sendForm" type="submit" class="btn btn-info" onclick="addComment()">Send</button>
        <button id="cancel" type="button" class="btn btn-warning" data-toggle="collapse" data-target="#openNew">Cancel</button>
    </div>

Answer â„–1

This code snippet will help you locate the div:

this.closest("li").querySelector("div[role='ucomment']")

In JavaScript, the closest() method only traverses upwards in the DOM hierarchy by selecting parent elements. Therefore, using it allows you to find the closest li element and then use the find() method with the selector div[role='ucomment'] within that li element.

// This script fetches all modify buttons as a NodeList and converts it into an array
const modifyBtns = Array.from(document.querySelectorAll('.btn.btn-modify'));

// Iterate over each button...
for (const modifyBtn of modifyBtns) {
  // Attach an event listener for the click event, binding the handler to each modifyBtn
  modifyBtn.addEventListener('click', modifyComment.bind(modifyBtn));
}

function modifyComment(e) {
  this.closest("li").querySelector("div[role='ucomment']").style.color= 'red';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="list-group-item d-flex justify-content-between align-items-center">
    <div class="row w-100">
      <div class="col-8" role="ucomment" name="ucomment1">{{ucomment}}</div>
    </div>
    <button type="button" class="btn btn-modify">Modify</button>
  </li>
  <!-- More list items here... -->
</ul>

Note: It appears that using inline event handlers like onclick may not pass the event correctly. As a solution, I've modified your code to utilize vanilla JavaScript instead of jQuery since closest behaves differently between the two libraries. Additionally, it's recommended to avoid inline event handlers and opt for addEventListener() for better practice.

Answer â„–2

If you want to trigger the modifyComment() function by clicking on a button, you can access the parent element and locate the specific div within it.

<button type="button" class="btn" onclick="modifyComment(this)">Modify</button>

    function modifyComment(elem) {
            let parent = $(elem).parent();

            parent.find($("div[role='ucomment']")).css("background", "red");
            console.log(parent);
        }

Alternatively, if you prefer to update the html of the button itself, you can make changes inside the modifyComment function:

$(element).parent().find("div[role='ucomment']").css("background-color","red")

Answer â„–3

Is it possible to achieve this with plain vanilla JavaScript?

document.getElementsByClassName("ucomment")[0];

Please let me know if this solution is effective.

You can then utilize jQuery's click function to identify the element being clicked and perform specific actions if it's a "div".

$("*", document.body).click(function(e) {
  e.stopPropagation();
  var element = $(this).get(0);
  if (element.tagName == "div") {
    //perform desired actions here
   }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it better to utilize a sizable JavaScript file or opt for a compact one?

I recently created a JavaScript file with over 6000 lines of code for various sections of my website. I'm debating whether to keep it as one large file or break it up into smaller parts and call them in their respective sections. What do you think? ...

Having issues with contenteditable functionality not functioning properly on elements that are dynamically generated

Creating an unordered list dynamically and adding items to it on a button click. Appending it to a section with contenteditable set to true, but encountering issues. The code snippet below demonstrates the process: // Create text input var categoryInput = ...

Leveraging the CSS-Element-Queries Library for emulating the functionality of CSS media queries

Recently, I used a nifty CSS-Element-Queries tool to perform basic element manipulations that trigger whenever the window is resized. In simple terms, my goal was to dynamically adjust an element's attribute based on the current width of the window â ...

Utilizing Sharepoint - accessing the Sp.Web.currentUser Property

I'm diving into a website I've been tasked to explore. While my HTML skills are limited, I'm eager to retrieve some SharePoint information using JavaScript. I launched my console and experimented with: var value = SP.Web.get_currentUser();, ...

Autocomplete for Converting Postal Codes to Cities

I'm currently working on a project that involves two input fields, as shown below: <div class="form-group{{ $errors->has('plz') ? ' has-error' : '' }}"> <label for="plz" class ...

Tips for Bridging the Space in a Horizontal Bootstrap Card

I'm in the process of designing a website that features a horizontal bootstrap card. I'm trying to figure out how to make the image on the left side of the card fill the full height of that section. Here's the code I'm working with: & ...

Tips for initiating a jQuery form submission

At this moment, the form is being submitted using the default URL. I would like it to utilize the form submit event in my JavaScript code so that it can pass the .ajaxSubmit() options. Below is the corresponding JavaScript code: $('#selectedFile&a ...

Calculating duration of ajax request

Is it feasible to measure the response time of an Ajax request? For instance, if data retrieval occurs in under 3 seconds, show a message and log the event using Ajax. If you can, please provide me with an example. P.S. Apologies for any language mistake ...

Do form validations affect the values assigned to ng-model objects?

If a form has the structure below: <form> <input type="text" required ng-model='myValue' ng-maxlength='5'></input> {{myValue}} {{myValue.length}} </form> Is there a way to prevent the model from b ...

Babel fails to substitute arrow functions

After setting up babel cli and configuring a .babelrc file with presets to es2015, I also installed the es2015 preset. However, when running the command babel script.js --out-file script-compiled.js, I noticed that arrow function syntax (=>) was still p ...

Eliminating replicated vertices in a Three.js geometry model

I'm struggling with removing duplicate vertices from a SphereGeomerty. I need to eliminate the seam on one side of the geometry as it doesn't align properly when updating the vertex positions. The issue arises when attempting to create a new geo ...

Staying connected with Ajax

I've developed a create_event.php page where users can input event details. After completing the form, they have the option to log in. Upon successful login, I aim to display 'Hello $username, you are now logged-in' without reloading the pag ...

Arranging based on attribute data

I'm currently working on organizing a collection of divs that have unique custom data attributes which I aim to sort based on user selection. For instance, if 'followers' is chosen, the .box elements will be arranged according to their data- ...

The JavaScript forEach loop is compatible with every web browser except for Internet Explorer

All browsers are working with the loop except for Internet Explorer, which does not seem to support forEach. Here is the JavaScript code: function validate() { var msg = ''; var i = 0; arr.forEach( function validateinfo(){ ...

Apply pointer style to the CSS only when a division contains text

If there is plain text inside a div with class="x95qze", how can we add cursor:pointer only to the second div that contains the text Cursor pointer required here. The div with class="x95qze" will not change. The content of the div may ...

Is there a way to merge two functions that are triggered by the same class name?

Whenever I click on an item inside my jQuery datatable, a function is triggered. $('.table tbody').on( 'click', '.item', function (e) { alert("clicked"); }); There is also another item with the same class outside the data ...

The behavior of the select menu is erratic when interacting with AJAX

My dropdown menu is populated dynamically based on AJAX response: function populateDropdown(dropdownNum) { // invokeWebService using $.ajax json = invokeWebService("GET", "/webservice/dropwdownOptions"); optionsHtml = ""; $.each(json, function(count, jsO ...

What is the Next.js equivalent of routing with rendering capability for nested component paths?

I am new to Next.js and so far have been loving the experience. I'm a bit stuck on how to achieve the equivalent of the following code in Next.js These are all client-side routes that render nested components on the user page. The value of ${currentP ...

How can we stop Vuetify from overwriting Bootstrap3's classes when using treeshaking?

I am currently in the process of transitioning an app from jQuery/Bootstrap3 to Vue/Vuetify. My approach is to tackle one small task at a time, such as converting the Navbar into its own Vue component and then gradually updating other widgets. Since the n ...

Vue paired with Rainyday.js

I attempted to incorporate Vue with rainyday.js by following different resources, but unfortunately could not find any relevant information. Can anyone provide guidance on how to successfully implement rainyday.js with Vue? <body onload="run();"> ...