Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I limit number of characters displayed in a div 1

Status
Not open for further replies.

Katie6

Programmer
Jun 12, 2007
58
GB
Hi there,

I have a web page with an include to a news article. So the whole news article is shown on the page. I would like only the first 200 characters to show, not the whole thing, so I have tried using the following code. However, I'm not having any success.

JavaScript
Code:
function limitLength(id,len){
var element = document.getElementById(id);
element.innerHTML = element.innerHTML(substr(0, len));
}

HTML:
Code:
<body onload="limitLength('myDiv',200);">
<div id="myDiv">Div contents</div>
</body>

Can anyone tell me where I'm going wrong?

Many thanks,

Katie
 
Fantastic - it works!
Thanks Feherke!
 
Do you know how I can add a ... to the end of the text?
At the moment the words are chopping off mid word.

Code:
e.g. the lady tripped over the c

It would be better if it said

Code:
the lady tripped over the c...

Many thanks for your help,

Katie
 
Hi

Code:
element.innerHTML = element.innerHTML.substr(0, len)+'...'
To not cut words remove the whole last word :
Code:
element.innerHTML = element.innerHTML.substr(0, len).replace(/\w*$/,'')+'...'

Feherke.
 
Ah, I see - that's much better! Thanks again Feherke. I've learnt something new :D
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top