michltm michltm - 7 months ago 22
PHP Question

Apply CSS to a number of divs defined with PHP

I have an array of strings with variable size.

For each elements in the array I'd like to separately be able to modify the size of the text they contain.

Right now it only works on the first sentence.

I would so something like

#trim <?= $i ?> {}


to be able to control each sentence but this doesent work.

What would be the optimal way to do that?

My code is the following:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>


<style>
#trim {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
position: relative;
padding-left:10px;
width: 50px;
}
#trim:after {
content: '+';
right: 0;
position: absolute;
}
#trim.full {
width: auto;
height: auto;
white-space: normal;
}
#trim.full:after {
display: none;
}
</style>


<?php

$array=['first sentence','sencond sentence','third sentence'];

$i=0;

foreach ($array as $answer)
{
?>

<p id="trim"><?= $answer ?></p>

<?php
$i++;
}
?>

<script>
$('#trim').click(function() {
$(this).toggleClass('full');
});
</script>

Answer

Id must be unique.

Reason why your code is not working.

If you are selection an element with id using an id selector like $('#trim') only first one will be selected.

Note: it is always better to use class instead of using same id.

Working demo using class

$('.trim').click(function() {
    $(this).toggleClass('full');
});
.full{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="trim">Para 1</p>
<p class="trim">Para 2</p>
<p class="trim">Para 3</p>
<p class="trim">Para 4</p>


You can use attribute selector if you are using id with same element. (Just for knowing.)

$('[id="trim"]').click(function() {
    $(this).toggleClass('full');
});

Working Demo

$('[id="trim"]').click(function() {
    $(this).toggleClass('full');
});
.full{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="trim">Para 1</p>
<p id="trim">Para 2</p>
<p id="trim">Para 3</p>
<p id="trim">Para 4</p>

Comments