0

$(document).click(function(){
  var i = 1;
  $("p:nth-child("+i+")").scrollintoview();
  i++;
});
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-scrollintoview/1.8/jquery.scrollintoview.js"></script>

<div class="parent">
  <div>
    <p>Hi</p>
  </div>
  <div>
    <p>Hi</p>
  </div>
  <div>
    <p>Hi</p>
  </div>
  <div>
    <p>Hi</p>
  </div>
</div>

I have here this code. I'm trying to make a search feature on every click. How can I search for these paragraphs one by one on every click with this structure of html. Is there any selector that will treat the ".parent" class as the parent element of these paragraphs? Thank you.

Muyie
  • 325
  • 1
  • 10

2 Answers2

1
  1. Declare i as a global.Then only its increment the value
  2. And use jquery eq() function its match the p index
  3. And target with .parent p
  4. Do with class add and remove for switching color

Updated with switching color

var i = 0;
$(document).click(function(){
  $('.parent').find("p").removeClass('yellow').eq(i).addClass('yellow')
  i++;
});
.yellow{
 background-color:yellow;
}
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>

<div class="parent">
  <div>
    <p>Hi</p>
  </div>
  <div>
    <p>Hi</p>
  </div>
  <div>
    <p>Hi</p>
  </div>
  <div>
    <p>Hi</p>
  </div>
</div>
prasanth
  • 19,775
  • 3
  • 25
  • 48
  • this almost do the trick. Is it possible to shift that highlight from one p to another? – Muyie Mar 10 '19 at 06:19
  • Thank you. But what if i want to scroll from one p to another? Sorry for not stating the main purpose on the problem. I'll edit it. – Muyie Mar 10 '19 at 06:31
  • check this answer .It will same as you need https://stackoverflow.com/questions/54803901/how-to-scroll-to-next-div-using-javascript/54804025#54804025 – prasanth Mar 10 '19 at 06:34
  • Will check that. Thank you – Muyie Mar 10 '19 at 06:36
1

Select all the paragraph elements and on click using i highlight them one by one

var i = 0;
$(document).click(function() {
$('p').css("background-color", "")
  $(Object.values($("p"))[i]).css("background-color", "yellow");
  i++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>

<div class="parent">
  <div>
    <p>Hi</p>
  </div>
  <div>
    <p>Hi</p>
  </div>
  <div>
    <p>Hi</p>
  </div>
  <div>
    <p>Hi</p>
  </div>
</div>
ellipsis
  • 11,498
  • 2
  • 13
  • 33