Search code examples
javascripttextrotator

Why does my code change ALL the p tags in my page?


This code

var current = 0,
    slides = document.getElementsByTagName("p");

setInterval(function() {
  for (var i = 0; i < slides.length; i++) {
    slides[i].style.opacity = 0;
  }
  current = (current != slides.length - 1) ? current + 1 : 0;
  slides[current].style.opacity = 1;
}, 1000);
p {
  position: absolute;
  transition: opacity .5s ease-in;
}

p + p { opacity: 0; }
<p>1</p>
<p>2</p>
<p>3</p>

is what I'm looking for to change the text on my page. However, when I add the p tags

<p>1</p>
<p>2</p>
<p>3</p>

all the paragraphs on the page will start to change. How can I specifically target just these three paragraphs tags?


Solution

  • Wrap the Ps in a container or give them a class and use querySelectorAll

    https://jsfiddle.net/mplungjan/nb7pkqy5/

    slides = document.querySelectorAll("#container p");
    

    var current = 0,
      slides = document.querySelectorAll("#container p");
    
    setInterval(function() {
      for (var i = 0; i < slides.length; i++) {
        slides[i].style.opacity = 0;
      }
      current = (current != slides.length - 1) ? current + 1 : 0;
      slides[current].style.opacity = 1;
    }, 1000);
    #container p {
      position: absolute;
      transition: opacity .5s ease-in;
    }
    
    #container p+p {
      opacity: 0;
    }
    <p>Other paragraph</p>
    
    <div id="container">
      <p>1</p>
      <p>2</p>
      <p>3</p>
    </div>