How to add class to specific number of increment div's child in php?

90
July 27, 2021, at 06:40 AM

As i am using a increment in PHP which output the number (1-unlimited) to div class ->

First of all let's see the code >>

  <?php $i = 0; ?>
        <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
    
    <div class="1-<?php echo ++$i ?>">
<h1 class="text">Demo</h1>
</div>
    
    <?php endwhile;

So i want to add a class to h1 or to div (like div class= 1-2 late) if div class is = 1-2 means how to add a class to h1 if increment number is two (2)

I expects

<div class="1-1">
    <h1 class="text">Demo</h1>
</div>
<div class="1-2">
    <h1 class="text class-here">Demo</h1>
</div><div class="1-3">
    <h1 class="text">Demo</h1>
</div>
Answer 1

EDIT after OP's clarification

To only output the class if its the second loop you need an if statement

<?php $i = 0; ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<?php $i++; // increment i by one ?>
<div class="1-<?php echo $i ?>">
    <h1 class="text <?php echo(($i = 2) ? ' some-class' : '') ?>">Demo</h1>
</div>

AGAIN: do not start your classes with a number. Start them with a letter.

ALSO: if you only want to add different styles to the second loop-items h1 you can simply use css for that. Give the wrapping div for all loop items a class like i.e. "article", then do this

.article:nth-child(2) h1 {
    /* your styles */
}

OLD ANSWER

Not sure if I get your question right but why don't you simply increment $i and then use it:

  <?php $i = 0; ?>
  <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
    <?php $i++; // increment i by one ?>
    <div class="1-<?php echo $i ?>">
        <h1 class="1-<?php echo $i ?> text">Demo</h1>
    </div>
<?php endwhile;>

Also if your wrapping div already has a class, you could simply access the h1 like this

.\32 1-2 h1

CSS identifiers should not start with a number, this can lead to trouble (which is why I am escaping it above). It's better to add a letter in front of the classname like

.wrapper-1-2
READ ALSO
Having trouble deploying React app with a server on Heroku

Having trouble deploying React app with a server on Heroku

I am having trouble deploying on Heroku my React app and serverI have successfully Deployed on Heroku before but for some reason, I forgot how to properly do it

75
pymysql error message (INSERT INTO function)

pymysql error message (INSERT INTO function)

I encountered error message (INVALID SYNTAX) and have no idea why it happensPlease help to figure it out

91
How can I format a String number to have commas in Kotlin?

How can I format a String number to have commas in Kotlin?

i have this code to calculate distance from 2 points(lat,lon)

76