Aeroy
Aeroy

Reputation: 25

How to combine getElementByTagName and getElementByClass using javascript

I am trying to make my selector so when it gets the class of transform with the tagname with p, it will do some event in my case it is mouse hovering but i am having trouble with it.

I know there are jquery solutions but i am doing it with pure javascript. here is the code below currently

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 
    }
}                   

Upvotes: 0

Views: 236

Answers (4)

gyre
gyre

Reputation: 16779

The vanilla JavaScript equivalent would be using 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>

However, I think the best approach would be to forego the JavaScript altogether and instead rely on the CSS pseudo-selector :hover:

body { background: #ccc; }

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

Upvotes: 0

BugHunter
BugHunter

Reputation: 1204

you can use classList to check class of element

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

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

Upvotes: 0

Ananth
Ananth

Reputation: 4397

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
    };
}

Upvotes: 0

rgthree
rgthree

Reputation: 7273

You can use a CSS selector in querySelectorAll to find all paragraphs with that classname:

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

Upvotes: 2

Related Questions