querySelectorAll.style does not work

后端 未结 3 1430
孤城傲影
孤城傲影 2020-12-03 23:49

I am writing something in JavaScript that I need to use querySelectorAll.style but it always returns undefined, but it works perfectly with querySelector.

相关标签:
3条回答
  • 2020-12-04 00:17

    querySelectorAll returns a html collection of elements, not a single element, so you need to loop over the results:

    Array.from(document.querySelectorAll("div#tabs" + tabId + "> div.page"))
        .forEach(function(val) {
            val.style.display = 'none';
    });
    
    0 讨论(0)
  • 2020-12-04 00:19

    querySelector:

    Returns the first element within the document...

    querySelectorAll:

    Returns a list of the elements within the document...

    IE in the first one, you're operating on a single element, which does have a style property. The second one is a list of elements, so you need to loop over that list applying the style:

    var els = document.querySelectorAll("div#tabs" + tabId + "> div.page");
    for (var x = 0; x < els.length; x++)
        els[x].style.display = 'none';
    
    0 讨论(0)
  • 2020-12-04 00:24

    querySelectorAll returns a list of elements rather than a single one.

    So this should work to apply the style to the first element found:

    document.querySelectorAll("div#tabs" + tabId + "> div.page")[0].style.display = 'none'; // First element
    
    0 讨论(0)
提交回复
热议问题