简体   繁体   中英

Setting title attribute for each summary tag if its parent details tag is open?

I would want to add a 'show' or 'hide' title for each summary tag which depends if its parent details tag is open:

<details open>
        <summary>Summary 1</summary>
        <p>text 1</p>
</details>

<details open>
        <summary>Summary 2</summary>
        <p>text 2</p>
</details>

I tried this but it only shows 'hide' even though the details is not set to open:

var detailsElem = document.getElementsByTagName('details');
var summaryElem = document.getElementsByTagName('summary');

for (i = 0; i < summaryElem.length; i++) {
  if (detailsElem[i].display === '') {
  summaryElem[i].title = 'show';
  } else {
  summaryElem[i].title = 'hide';
  }
}

I assume you are trying to access element css property. If so, then this line is wrong detailsElem[i].display === '' .

It should be detailsElem[i].style.display .

Also display cannot be empty and values can be either display , inline , inline-display , none ...

Here's the better solution to access element css property. Use getComputedStyle() method to get computed styles

var detailsElem = document.getElementsByTagName('details');
var summaryElem = document.getElementsByTagName('summary');

for (i = 0; i < summaryElem.length; i++) {
  var style = getComputedStyle(detailsElem[i]);
  if (style.display === 'none') {
    summaryElem[i].title = 'show';
  } else {
    summaryElem[i].title = 'hide';
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM