1

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>
2
  • Won't x.innerText = x.substring(0,10); do what you want? Commented Mar 9, 2013 at 0:32
  • 2
    Using innerText will fail in Firefox. Either use jQuery or another library that covers up these differences, or feature-detect for the usage of textContent instead of innerText. Commented Mar 9, 2013 at 0:37

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1
<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>

Demo

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.