Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set an additional class to a dynamically created div

Tags:

html

php

function givemetitles($table){
    global $db;
    $titles = '';
    $stmt = $db->query("SELECT id, title FROM " . $table . " ORDER BY title ASC");
    while($row = $stmt->fetch()){
        $titles.= 
                  "<div data-id=" . $row['id'] . 
                  " class='linkl'>" . $row['title'] . "</div>\n"; 
     }
     echo $titles;
}

This writes the divs with linkl class successfully.

I need the first div to also contain the class linklactive - if possible.

like image 420
qadenza Avatar asked Feb 22 '26 23:02

qadenza


2 Answers

Another approach is to set the class, and then clear it:

function givemetitles($table){
    global $db;
    $titles = '';
    // set $first_class to the class you want for the first record
    $first_class = ' linklactive';
    $stmt = $db->query("SELECT id, title FROM " . $table . " ORDER BY title ASC");
    while( $row = $stmt->fetch() ) { 
        // include $first_class in the $title value
        // tweaked to use string interpolation
        // Switched to PHP_EOL instead of \n
        $titles.= "<div data-id='{$row['id']}' class='linkl{$first_class}'>{$row['title']}</div>" . PHP_EOL;
        // reset $first_class to be empty string
        $first_class = ''; 
    }

    echo $titles;    
}
like image 88
random_user_name Avatar answered Feb 24 '26 11:02

random_user_name


You can just count how many times you have looped, in the first run, you add that class...

function givemetitles($table,$row_active = 0){

    global $db;
    $titles = '';
    $stmt = $db->query("SELECT id, title FROM " . $table . " ORDER BY title ASC");
    $count = 0;
    while($row = $stmt->fetch()){
        if($count == $row_active){
            $titles.="<div data-id=" . $row['id'] . " class='linkl linklactive'>" . $row['title'] . "</div>\n";
        }else{
            $titles.="<div data-id=" . $row['id'] . " class='linkl'>" . $row['title'] . "</div>\n";
        } 
        $count++;
    }
    echo $titles;

}

Pretty? No not really, but it does the job.

That said, in this case the cale_b answer is more on point and "prettier". I am keeping this answer as you can define which row gets the class.

like image 36
Nytrix Avatar answered Feb 24 '26 11:02

Nytrix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!