Reputation: 13
I have a heading on my webpage that I want to limit to a certain number of characters. The heading is for a blog post so the title changes. This is essentialy what I want to accomplish.
<body>
<script>
var x= document.getElementById("entry-title");
document.write(x.substring(0,10));
<script>
<h1 id="entry-title">This is a sample blog title</h1>
</body>
Upvotes: 1
Views: 1571
Reputation: 11351
try that
<body>
<script>
window.onload =
function (){
var x= document.getElementById("entry-title");
x.innerText = x.innerText.substring(0,10);
}
</script>
<h1 id="entry-title">This is a sample blog title</h1>
</body>
There the code with jquery
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js" ></script>
</head>
<body>
<script>
$(document).ready(
function (){
var text = $("#entry-title").text();
var x= $("#entry-title").text(text.substring(0,10));
}
);
</script>
<h1 id="entry-title">This is a sample blog title</h1>
</body>
</html>
Upvotes: 1
Reputation: 70159
<h1 id="entry-title">This is a sample blog title</h1>
<script>
(function() {
var el = document.getElementById("entry-title"),
supportedProp = el.textContent != null ? 'textContent' : 'innerText';
el[supportedProp] = el[supportedProp].substring(0, 10);
}());
</script>
You have to either place your script below the element that you want to reference or defer its execution with a DOMContentLoaded
or window load
event handler.
Also, the W3C standard property is textContent
instead of IE's proprietary (and adopted by Chrome) innerText
property. Therefore you need to do some feature detection if you want to support both Firefox and IE. Chrome accepts either of the properties.
Upvotes: 1