'Selecting the value of specific element with the same class as others

    <body>
        <div class = "element">
            Monday - <button class= "delete_button">Delete</button>
        </div>
        <div class = "element">
            Tuesday - <button class= "delete_button">Delete</button>
        </div>
        <div class = "element">
            Wednesday - <button class= "delete_button">Delete</button>
        </div>
    </body>

For that HTML I have a JavaScript file with function with onclick event listener for class= "delete_button" and the goal is to get in JavaScript variable the value of the specific div in which is the button that has been pressed.



Solution 1:[1]

With the JS function parentElement and split you can do it as well.

function deleteThis (e) {
  const v = e.parentElement.innerText.split('-')
  console.log('The value from div is: ', v[0])
  alert(v[0])
}
  <body>
        <div class = "element">
            Monday - <button class= "delete_button" onclick="deleteThis(this)">Delete</button>
        </div>
        <div class = "element">
            Tuesday - <button onclick="deleteThis(this)" class= "delete_button">Delete</button>
        </div>
        <div class = "element">
            Wednesday - <button onclick="deleteThis(this)" class= "delete_button">Delete</button>
        </div>
    </body>

small note Try to avoid to use the onclick element. Better to bind the buttons to a EventListener..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maik Lowrey