简体   繁体   中英

Get CSS property of <ul> <li> child node with vanilla javascript

How can I get CSS properties of an child element of a node? I want to get the height of the <li> element of a <ul>

style.scss

ul.menu {
   width: 100%;
   float: left;
   li {
      height: 28px;
    }
}

javascript

let elementList = this.dropdownMenu.nativeElement.children;
console.log(elementList.length);
console.log(/*height of li*/);

I prefer solutions with vanilla JavaScript without using jQuery!

For your case, where the html looks like:

<ul class="menu">
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>

And css:

ul.menu {
   width: 100%;
   float: left;
}

ul.menu li {
  height: 28px;
}

Your working javascript should be:

var list = document.getElementsByClassName("menu")[0];

for (var i = 0; i < list.children.length; ++i) {
    var clientHeight = list.children[i].clientHeight,
        offsetHeight = list.children[i].offsetHeight;
    console.log(clientHeight); // with padding
    console.log(offsetHeight); // with borders
}

See also this answer .

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