【问题标题】:Change style of an element in a forEach loop在 forEach 循环中更改元素的样式
【发布时间】:2022-08-12 22:50:30
【问题描述】:

目标:更改 forEach 循环中元素的样式
问题:未应用样式

在我的循环中,如果我使用 console.log(element),我会得到正确的过滤元素列表。
运行这个工作,但我希望我的函数修改与我的过滤器匹配的每个元素:

let contentPreview = document.querySelectorAll(\'.o_last_message_preview\');
contentPreview[0].style.color = \'yellow\'

所有元素均已正确分配。

function changeNotificationColor() {
        // Notification button that opens list of notifications
        let notifyButton = document.querySelector(\'.dropdown-toggle.o-no-caret[title=\"Conversations\"]\');

            notifyButton.addEventListener(\'click\', function () {
            // List of notifications - each notification is contained in a .o_last_message_preview class
            let contentPreview = document.querySelectorAll(\'.o_last_message_preview\');

            contentPreview.forEach(function (element) { if (element.innerText.includes(\'Marine\')) {element.style.color = \'yellow\'}})
        })
    }

changeNotificationColor();

    标签: javascript


    【解决方案1】:

    我不知道您的问题是什么,但这不在您显示的代码中;这工作正常:

    let contentPreview = document.querySelectorAll('.o_last_message_preview');
    
    contentPreview.forEach(function (element) { if (element.innerText.includes('Marine')) {element.style.color = 'yellow'}})
    <div class="o_last_message_preview">This contains Marine</div>
    <div class="o_last_message_preview">This does not</div>
    <div class="o_other_message_preview">This has a different class</div>

    【讨论】:

      猜你喜欢
      • 2015-10-10
      • 2021-12-31
      • 2021-12-06
      • 2020-11-26
      • 2019-06-03
      • 2021-12-07
      • 2018-06-10
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多