How to display string length in javascript - 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

Related

Javascript display all (elements, tags) from method elementsbyTagName

Im learning JavaScript and i have problem with DOM methods.
HTML
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="DOM_Ponovno.js"></script>
</head>
<body>
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
</body>
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
document.write(tmpTag[i].textContent);
}
}
If i follow the tutorial its ok, but i wanted to display all elements by tag name p. I want to display all paragraphs stored in tmpTag.
Someone please explain:
How can ( why cant) display all elements with tag name p ?
How can (why cant) display 3x p tag from variable tmpTag ?
Tried to change to Array with prototype.slice.call method but no success.
You know like Java stuff loop through display/change at index etc..
Thank you :)
Hi and thanx for fast answers.. Sory about the function name it was for testing... I just want to display all elements by tag name p. This code displays only first element and i counter in for loop stops at 1. Why cant i get other 2 paragraph elements ?
Im using document.write like system.out.print in Java to see whats in array. I know if i wanna change i need innerHTML.
If you are wanting to update each paragraph, do not use document write. Try the following:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
tmpTag[i].innerHTML = "Your new updated text to change it to for tag index " + i + "...";
}
}
As #Juhana mentioned, the moment you start your loop you overwrite the document using document.write, so all your p tags get removed from the document and replaced by the text in the first paragraph and then your function fails, as the now-empty objects don't have any textContent property. You could concatenate all the contents and write it once:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var print = '';
for(var i = 0;i< tmpTag.length;i++) {
print += tmpTag[i].textContent;
}
document.write(print)
}
But actually, just don't use document.write - SO snippets don't even allow it anymore! Here a way with a div as output:
var output = document.getElementById('output');
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
output.textContent += tmpTag[i].textContent;
}
}
<div>
<p id="demo" >this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
<div id="output"></div>
I'm not sure what you're trying to do but you can add another div for result with id='result' and append result you want to it, check following example.
Hope this will help.
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var result = document.getElementById('result');
for(var i = 0;i< tmpTag.length;i++) {
result.innerHTML += tmpTag[i].textContent+'<br>';
}
}
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
<br>
<div id="result" ></div>
</div>

manipulating tag using java script

I am fairy new in learning JavaScript , I am practising to manipulate a tag,
here is my code
I know that I am making a silly mistake here but I am not sure which part has went wrong ?
could any one please give me some hint ?
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Hyperlinks
</title>
</head>
<body>
<h1>
HTML Hyperlinks
</h1>
<p>
Here is a link to <a name = "hyper" href="http://yahoo.com/">page</a>.
The text around the link is not part of the link.
</p>
<script>
var element = document.getElementsByTagName("a");
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
</body>
</html>
getElementsByTagName says elements. Plural.
It returns a NodeList, which is like an Array, not a single Element.
You need to loop over its return value (e.g. with for) or access it by index ([0])
You are requesting a collection of a tags, but then treating them like a single entity.
<script>
var element = document.getElementsByTagName("a");
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
try this
<script>
var element = document.getElementsByTagName("a")[0];
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
or
<script>
var elements = document.getElementsByTagName("a");
for(var i = 0; i < elements.length; i++)
{
var element = elemenets[i];
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
}
</script>
Change this line
var attribute = element.getAttribute("href");
to this
var attribute = element[0].getAttribute("href");

Javascript - Replace html using innerHTML

I'm trying to replace html using innerHTML javascript.
From:
aaaaaa/cat/bbbbbb
To:
Helloworld
This's my code
<html>
<head>
</head>
<body>
<p id="element1">aaaaaa/cat/bbbbbb</p>
<script language="javascript">
var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML.replace( /aaaaaa./g,'<a href=\"http://www.google.com/') ;
strMessage1.innerHTML = strMessage1.innerHTML.replace( /.bbbbbb/g,'/world\">Helloworld</a>') ;
</script>
</body>
</html>
When i run this code it disappears Helloworld hyperlink.
what I'm doing wrong. Please help.
Thank you for all your help.
You should chain the replace() together instead of assigning the result and replacing again.
var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
.replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
.replace(/.bbbbbb/g,'/world\">Helloworld</a>');
See DEMO.
You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:
var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;

Javascript variable access in HTML

Say I have the following JavaScript in a HTML page
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
</script>
<body>
<a href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
How do I get the value of the variable "splitText" outside the script tags.
Thanks!
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myLink").innerHTML=splitText;
}
</script>
<body>
<a id="myLink" href = test.html></a>
</body>
</html>
Try this :
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
$("#target").text(splitText);
});
</script>
<body>
<a id="target" href = test.html></a>
</body>
</html>
<html>
<head>
<script>
function putText() {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
}
</script>
</head>
<body onLoad = putText()>
<a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
In raw javascript, you'll want to put an id on your anchor tag and do this:
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
function insertText(){
document.getElementById('someId').InnerHTML = splitText;}
</script>
<body onload="insertText()">
I need the value of "splitText" variable here
</body>
</html>
Here you go: http://codepen.io/anon/pen/cKflA
Although, I must say that what you are asking to do is not a good way to do it. A good way is this: http://codepen.io/anon/pen/jlkvJ
The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph).
Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.
Example:
<!DOCTYPE html>
<html>
<body>
<!--\|/id here-->
<p id="myText"></p>
<p id="myTextTag"></p>
<script>
<!--Here we retrieve the text and show what we want to write...
var text = document.getElementById("myText");
var tag = document.getElementById("myTextTag");
var toWrite = "Hello"
var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"
<!--...and here we are actually affecting the text.-->
text.innerHTML = toWrite
tag.innerHTML = toWriteTag
</script>
<body>
<html>

stuck with javascript-html output

I am kind of stuck in weird problem. i cant find the problem with the following code
<html>
<head>
<script type="text/javascript">
// Import GET Vars
document.$_GET = [];
var urlHalves = String(document.location).split('?');
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
document.$_GET[urlVarPair[0]] = urlVarPair[1];
}
}
}
var tag_tag=document.$_GET['tags'];
alert(tag_tag);
document.getElementById("resultElem4").innerHTML=tag_tag;
</script>
</head>
<body>
<p id='resultElem4'></p>
</body>
</html>
its showing the string in alert but not in html when i call it like result.php?tags=cat
Put your script tag at the bottom (right before the closing body tag). The issue is that the element resultElem4 hasn't loaded when you try to reference it using getElementById.
You just move the < script > to the end of the body.
<body><p></p><script>....</script></body>

Categories