Home > database >  get dataset from parent
get dataset from parent

Time:11-08

I have the element inside this structure:

<div data-unit="5" data-id="0" id="unit-0" class="session-unit-container unit-columns">
  <h1 class="unit-title">5</h1>
  <div class="session-unit">
    <div id="element" class="session-card" draggable="false" style="">Item 5</div> // here is the element
  </div>
</div>

How can I get the data-unit="5" of the parent element when I select the element?

CodePudding user response:

I don't understand what you mean by saying when I select the element. You mean when you click? When you mouse select the text?

Anyway, the way to access the value is the following:

// Here I select the element I am interested for.
let element = document.getElementById('element');

// Here I just console.log the value of the data-unit
console.log(`Here Is The data-unit Value: ${element.parentNode.parentNode.dataset.unit}`);
<div data-unit="5" data-id="0" id="unit-0" class="session-unit-container unit-columns">
  <h1 class="unit-title">5</h1>
  <div class="session-unit">
    <div id="element" class="session-card" draggable="false" style="">Item 5</div> // here is the element
  </div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Assuming you have more than one container containing cards you can attach a listener to each container and, if the element you clicked on was a card, log the value of the data attribute.

(Note: if you do have multiple containers of cards don't give each card the same id.)

// Cache the container elements
const containers = document.querySelectorAll('.session-unit-container');

// Add listeners to them
containers.forEach(container => {
  container.addEventListener('click', handleClick, false);
});

function handleClick(e) {

  // Get the class list from the element that was clicked
  const { classList } = e.target;

  // If it's a card...
  if (classList.contains('session-card')) {

    // Locate the container element
    const parent = e.target.closest('.session-unit-container');

    // And get its unit value from the dataset
    const { unit } = parent.dataset;

    console.log(unit);

  }

}
.session-card:hover { cursor: pointer; color: red; }
<div data-unit="2" data-id="0" id="unit-0" class="session-unit-container unit-columns">
  <h3 class="unit-title">2</h3>
  <div class="session-unit">
    <div class="session-card" draggable="false" style="">Item 2</div>
  </div>
</div>
<div data-unit="5" data-id="0" id="unit-0" class="session-unit-container unit-columns">
  <h3 class="unit-title">5</h3>
  <div class="session-unit">
    <div class="session-card" draggable="false" style="">Item 5</div>
  </div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Additional documentation

  • Related