I have a list with p tags inside. I want to get the size of each text and then crop it. I have this:
<script>
var text;
for(var i=0;i<document.getElementsByTagName("p").length;i++){
console.log(document.getElementsByTagName("p")[i].length+ "");
if(text[i].length > 12) {
text[i] = text[i].substring(0,10)+"...";
}
}
</script>
The problem is that it gives me undefined. I also had another question. Where should I put this piece of code, inside the head or at the end of the body? Would it be better to do it with jQuery?
For the variable to
texto
store the size, you have to create a variable (elementos
for example) that collects the array returned by the functiongetElementsByTagName("p")
Then you initialize
textos
as an array with number of elements equal to the number of elements obtained.Then you iterate as you did, but you can't do a
.lenght
directly but you have to access the propertyinnerHTML
that collects the text between the labels<p>
and</p>
Inside the
if
where you check if it is>12
you have to put theelementos[i].innerHTML
in the left part of the assignment to change its content. (although I don't understand why the put check12
and thesubstring
put10
)Regarding where to put it, you can put this in a function that is called in the event
onLoad
Based on your example:
Of
jQuery
course it would be easier if you used it.Example with jquery: