如何使用javascript结合getElementByTagName和getElementByClass

时间:2017-03-24 18:55:13

标签: javascript

我正在尝试创建我的选择器,所以当它获得带有p的标记名的变换类时,它会在我的情况下做一些事件,它是鼠标悬停但我遇到了麻烦。

我知道有jquery解决方案,但我正在使用纯javascript。这是目前的代码

var hoverEvent = document.getElementsByTagName("p").getElementsByClassName("transform");   

for (let i = 0; i < hoverEvent .length; i++) {
    hoverEvent [i].onmouseover=function() {
        this.style.color = "yellow";
     // changes paragraph with class of transform to yellow during hover
    }
}  // end for  

    for (let i = 0; i < hoverEvent .length; i++) {
    hoverEvent [i].onmouseout=function() {
        this.style.color = "black";
 // changes it back to black 
    }
}                   

4 个答案:

答案 0 :(得分:2)

您可以使用querySelectorAll中的CSS选择器查找具有该类名的所有段落:

var hoverEvent = document.querySelectorAll("p.transform");   

答案 1 :(得分:0)

var transformPs = document.querySelectorAll("p.transform");   

for (let i = 0; i < transformPs .length; i++) {
    // on mouse over
    transformPs[i].onmouseover = function () {
        this.style.color = "yellow";
        // changes paragraph with class of transform to yellow during hover
    };

    // on mouse out
    transformPs[i].onmouseout = function () {
        this.style.color = "black";
        // changes it back to black
    };
}

答案 2 :(得分:0)

vanilla JavaScript等价物将使用document.querySelectorAll

function turnYellow (e) { e.target.style.color = 'yellow' }

function turnBlack (e) { e.target.style.color = '' }

document.querySelectorAll('p.transform').forEach(function (p) {
  p.addEventListener('mouseover', turnYellow)
  p.addEventListener('mouseout', turnBlack)
})
body { background: #ccc; }
<p class="transform">Example Paragraph</p>

但是,我认为最好的方法是完全放弃JavaScript,而是依赖CSS伪选择器:hover

body { background: #ccc; }

p.transform:hover {
  color: yellow;
}
<p class="transform">Example Paragraph</p>

答案 3 :(得分:0)

您可以使用 classList 来检查元素类

var p = document.getElementsByTagName("p");

if (p.classList.contains('transform')){ 
// do whatever you want to do 
}