Use javascript substring to specify character length - javascript

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>

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>

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

Related

How to display string length in javascript

I am new to javascript, and today i was trying my first example as shown below in the code section. I am using an editor called "Free Javascript Editor".
when I run the code, the browser starts and the text between the tags is displayed but the length of the string is never shown.
am I using it wrong?? please let me know how to do it correctly
lib
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
code:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = new string ("MyString");
str.length;
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Use Onload event and put it inside js function.
<body onload="myFunction()">
<script>
function myFunction() {
var str = ("MyString");
var n = str.length;
document.getElementById("printlength").innerHTML = n;
}
</script>
<h2>My First JavaScript</h2>
<p id="printlength"></p>
</body>
Use document.createElement
var str = "MyString";
var p = document.createElement("p");
p.textContent = str.length;
document.body.appendChild(p);
Scripts are not rendered by the browser, only executed. You can, however, do something like this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<h2>My First JavaScript</h2>
<p id="theLength"></p>
<script>
// No need to invoke the string constructor here.
var str = 'MyString';
// Find our placeholder element and set the textContent property.
document.getElementById('theLength').textContent = str.length;
</script>
</body>
</html>
It's good practice to put your script tags at the end of the body element - that way all of the HTML should render before the scripts are executed.
You should assign the length of your string to a variable. Then, you can show it.
<span id="stringLength"></span>
<script>
var str = "MyString";
var length = str.length;
document.getElementById('stringLength').textContent = 'Length: ' + length; // Show length in page
console.log('Length: ' + length); // Show length in console
alert('Length: ' + length); // Show length as alert
</script>
It must be String, not string. Code below works.
var str = new String ("MyString");
str.length;
Changed your code to this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = "MyString";
console.log(str.length);
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Then you must look in the developer console for the output, here is how:
Google Chrome
FireFox
Safari

Printing object property in an html paragraph

I should get an output of "Peter" in the paragraph with id="para1", but somehow, this is not happening. Can someone help me out?
<html>
<head>
</head>
<body>
<p id=para1></p>
<script>document.getElementById('para1').innerHtml = alpha.name;</script>
<script>
var alpha = {name:"Peter",age:23,gender:"male"};
</script>
</body>
</html>
I've changed the code to this, still cannot see the word "Peter" in the html screen:
<html>
<head></head>
<body>
<p id=para1></p>
<script>
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHtml = alpha.name;
</script>
</body>
</html>
There are two mistake you have.
First: <p id=para1></p> id must have " like <p id="para1"></p>
Second: innerHTML not innerHtml
Check your updated code here:
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
<p id="para1"></p>
Your main mistake is innerHtml instead innerHTML. But all your code is not good formatted.
Let's change your code
<p id="para1"></p>
<script type="text/javascript">
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
</script>
You're trying to call the object before it exists. Either change your script around, or use window.onload:
<script type="text/javascript">
window.onload = function(){
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
};
</script>
This makes sure that the page is fully loaded before the scripts gets executed.
This is by far the best and safest solution, but if you rather leave it to "load as you go", then changing the order would (perhaps) be sufficient:
<p id="para1"></p>
<script type="text/javascript">
var alpha = {name:"Peter",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
</script>
Edit:
Also, as others mentioned - it's .innerHTML. Javascript is case sensitive.
<html>
<body>
<p id="para1"></p>
<script>
var alpha = {name:"Peter",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
</script>
</body>
</html>

can any one explain and provide the correct the code?

The HTML file has:
<html>
<head>
<title>title</title>
<script style="text/css" src=".\Scripts\CSS\tryc.css"></script>
<script style="text/javascript" src=".\Scripts\JavaScripts\Text8.js"></script>
</head>
<body id="body">
<h1 id="heading1">Coming Soon</h1>
<object id="circle-svg" width="1300" height="560" type="image/svg+xml" data=".\Scripts\svg\ulti.svg"></object>
</body>
</html>
The JavaScript has
window.onload = function () {
var as = document.getElementById("body");
var as1 = as.getElementById("heading1");
as1.style.color = "blue";
alert(as1);
alert("try");
};
The text does not turn blue.
getElementById must always be called from a document object.
var as = document.getElementById("body");
var as1 = as.getElementById("heading1");
var as1 = document.getElementById("heading1");
No nested context is needed, because IDs must be unique within the document.
And FWIW, you can use document.body instead of putting an ID on the body.
Oh, also you should use forward slashes instead of backslashes to get your script.
<script type="text/javascript" src="./Scripts/JavaScripts/Text8.js"></script>
I dont think you can use
as.getElementById();
Why dont you go directly with:
as = document.getElementById('heading1');
as.style.color = 'blue';

not able to load contents in div using javascript

this is shan and i'm a javascript noob and i'm trying to work qa code as an example here. i'm trying to load a small javascript content to a div element but it is not working any help would be great and here is the code.
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext () {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerhtml="adding 1 to 100 gives "+sum;
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
You need to call the function. It's also a good idea to wait until the window is loaded (or you can use some more advanced JS to detect the DOM ready state.):
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext() {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML = "adding 1 to 100 gives "+sum;
}
window.onload = function(){
displaytext();
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
3 problems:
You never actually call the function. It is only declared.
The property is innerHTML not innerhtml. Javascript is case-sensitive.
The script is above an element is is referencing. As scripts are executed as they are found (page construction is paused during execution) the element you are referring to is never found.
Also you declare the loopindex variable twice, which i think will cause a syntax error on ES5 strict.
<html>
<head>
<title>
using d for statement
</title>
</head>
<body>
<div id="targetdiv">
</div>
</body>
<script>
function displaytext () {
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML="adding 1 to 100 gives "+sum;
}
displaytext();
</script>
</html>

Why does the browser modify the ID of an HTML element that contains &#x?

Say I've got this HTML page:
<html>
<head>
<script type="text/javascript">
function echoValue(){
var e = document.getElementById("/path/$whatever");
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>
I would assume that the browser treats the ID-string /path/$whatever as simple string. Actually, it converts the $ to it's rendered representation ($).
The javascript code however uses the literal string $ to search for the element. So, the call document.getElementById fails and I never get hands on the value of the paragraph.
Is there a way to force the browser into using the given ID string literally?
Edit:
Of course I know that I don't have to escape the $. But the web page gets generated and the generator does the escaping. So, I have to cope with what I've got.
In the <p id="...">, the $ sequence is interpreted as $, because it appears in an attribute and is treated as an HTML entity. Same goes for all other element attributes.
In the <script> element, HTML entities are not interpreted at all, so it shows up literally.
You could try decoding the javascript text without jQuery:
<html>
<head>
<script type="text/javascript">
function decodeEntity(text){
text = text.replace(/<(.*?)>/g,''); // strip out all HTML tags, to prevent possible XSS
var div = document.createElement('div');
div.innerHTML = text;
return div.textContent?div.textContent:div.innerText;
}
function echoValue(){
var e = document.getElementById(decodeEntity("/path/$whatever"));
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>
JSFiddle: http://jsfiddle.net/phTkC/
I'd suggest you to decode the HTML entity in your javascript code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
function echoValue(){
var decoded_string = $('<div />').html("/path/$whatever").text();
var e = document.getElementById(decoded_string);
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>

Categories