I have written a simple code that runs properly in console, but is not reflecting the property of object in code, I cant make out whats wrong with the code:
<html>
<head>
<script>
function alpha(){
var x = {name:"Sunil",age:37,gender:"male"};
document.getElementById('para1').innerHTML(x.name);
console.log(x.name);
}
</script>
</head>
<body>
<button id=but1 onclick=alpha()>Click Me</button>
<p id=para1> This is paragraph One. </p>
</body>
</html>
Kindly, denote where am I wrong, as console is working fine with same code if I remove #para1 line from head!
Thanks in advance!
innerHTML is not a method, it's a property. Assign the text to the property:
document.getElementById('para1').innerHTML = x.name;
Related
I need to get all the content of page including all codes on JavaScript alert. Please check the code.
function getContent() {
var content = document.getElementsByTagName('html').value;
alert(content);
}
<html>
<head>
</head>
<body>
Some more code..........
Get Content
</body>
</html>
I am trying to execute the function from inside the page and trying to get the value. It is giving me undefined error
.getElementsByTagName() returns a NodeList collection of elements. You need to access the first index with [0]. In addition to this, it does not have a .value property. You're looking for .innerHTML instead.
Note that you also shouldn't make use of onclick, and instead should make use of unobtrusive JavaScript by adding an event listener.
This can be seen in the following:
function getContent() {
var content = document.getElementsByTagName('html')[0].innerHTML;
alert(content);
}
document.getElementsByTagName('a')[0].addEventListener('click', getContent);
<html>
<head></head>
<body>
Some more code..........
Get Content
</body>
</html>
Note: this will not work as expected in a Fiddle, but will work as expected on a proper website.
This can be achieved via the innerHTML field of a DOM element. Consider making the following changes to your getContent() function:
function getContent() {
var { innerHTML } = document.querySelector('html');
alert(innerHTML);
}
<html>
<head>
</head>
<body>
Some more code..........
<p> and some more content </p>
Get Content
</body>
</html>
I want this code to replace all ':)'s with my smiley emoji. Although when I run the code I get Uncaught TypeError: Cannot read property 'replace' of undefined at ?v=0.02:10 any help would be greatly appreciated!
Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>SVG Emoji</title>
</head>
<body>
<script>
var html = document.getElementsByTagName("html").innerHTML;
html.replace(":)", "<img src='https://csf30816.github.io/svg-emoji/emojis/smile.svg'>");
document.getElementsByTagName("html").innerHTML = html;
</script>
<h1>:) Test</h1>
</body>
</html>
Replace
document.getElementsByTagName("html").innerHTML
with
document.getElementsByTagName("html")[0].innerHTML
as getElementsByTagName returns an array.
Also, the string.replace() method returns a new string without mutating / modifying the given one. You would need to re-assign the returned string to html = html.replace(...).
Also, you need to move your <script> to the bottom. Otherwise it can't access DOM elements that appear beneath it in your HTML document, such as the <h1> element:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>SVG Emoji</title>
</head>
<body>
<h1>:) Test</h1>
<script>
var html = document.getElementsByTagName("html")[0].innerHTML;
html = html.replace(":)", "<img src='https://csf30816.github.io/svg-emoji/emojis/smile.svg'>");
document.getElementsByTagName("html")[0].innerHTML = html;
</script>
</body>
</html>
See also How to get the <html> tag HTML with JavaScript / jQuery?
For a more robust approach to replacing text within the DOM see jQuery replace all occurrences of a string in an html page
Your code and the problem you are trying to solve are doing different things. This will give you the solution you are seeking, i.e. replace all ':)'s with my smiley emoji
function replaceTextByImage(pattern, src) {
document.body.innerHTML = document.body.innerHTML.replace(
new RegExp(pattern, 'g'),
'<span style="background-size: 100% 100%; background-image: url(\'' + src + '\');">    </span>'
);
}
replaceTextByImage(':\\)', 'https://csf30816.github.io/svg-emoji/emojis/smile.svg');
replaceTextByImage(':P', 'https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/svg/1f61b.svg');
replaceTextByImage(':D', 'https://what.thedailywtf.com/plugins/nodebb-plugin-emoji-one/static/images/1f603.svg');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<p>
Hello World! How are you? :). Do you like this emoji :)
</p>
<div style="font-size:50px;">How about now :)</div>
<div style="font-size:25px">You can also do this :P and this :D now!</div>
</body>
</html>
PROS
Emoji will resize according to font used.
Replaces all occurrences of a pattern
CONS
If you have an inline script in the body of your html, it may be re-executed every time the function replaceTextByImage is called because it is setting the body's innerHTML.
If you want to use jquery then don't read this answer.
But for those who can allow their script not be jquery,
Here is your code.
document.getElementsByTagName("H1")[0].innerHTML = '<img src="https://csf30816.github.io/svg-emoji/emojis/smile.svg">';
<h1>:) Test</h1>
What the problem is:
You are returning an array.
Use one element with [0]:
document.getElementsByTagName("html")[0].innerHTML = html;
I'm trying to get a simple javascript function to work. I know enough Javascript to think to myself, "This should work, Why isn't it working!" I'm sure we've all been there before. I have done some research to brush up on my functions and to compare my function to but to no avail, I still can't get this function to work. I'm using Javascript to try to display my name within a span element. Normally this should be easy but, for some reason it just isn't working. This is also done in a .php file and a .html file. Because i wanted to make sure it didn't matter if it was a .php file or .html file. It won't work in either. This is for a php project by the way.
Here's the code
<html>
<head>
<script>
var yourName = "Robin";
function placeName()
{
document.getElementById("myName").innerHTML = yourName;
}
</script>
</head>
<body>
<h1>PHP Basics</h1>
<h2>Hi! My Name is<span id = "myName"></span>
</body>
</html>
Like I said, This should be simple, but it won't work. I'm hoping a new set of eyes (you guys) would be able to point out my rookie mistake. If I need to explain anything in more detail please let me know. And thank you all very much.
You're not running the function. Be careful, only run the function after the span has been created or else it will not work. See this example.
<html>
<head>
<script>
var yourName = "Robin";
function placeName()
{
document.getElementById("myName").innerHTML = yourName;
}
</script>
</head>
<body>
<h1>PHP Basics</h1>
<h2>Hi! My Name is<span id = "myName"></span>
<script>
// run function
placeName();
</script>
</body>
</html>
You have made the body of the function but you haven't call the function so that it will be executed. You can do it like this
<html>
<head>
</head> <body> <h1>PHP Basics</h1> <h2>Hi! My Name is<span id = "myName"></span> </body> </html>
var
yourName = "Robin";
function placeName() {
document.getElementById
("myName").innerHTML
= yourName; }
placeName();
// it won't return undefined try it
When you search for how to set a paragraph or header element's text dynamically, you keep coming across pretty much the same line of code:
document.getElementById("header").innerHTML = "some text";
This isn't entirely correct though. Take the following example:
<html>
<head />
<body>
<h1 id="header" />
<p id="p1" />
<script type="text/javascript">
document.getElementById("header").innerHTML = "header";
document.getElementById("p1").innerHTML = "p1";
</script>
</body>
</html>
The first JavaScript line pretty much deletes p1 from the page, even though p1 and header have nothing to do with each other in the raw HTML. When wrapping the second JavaScript line in a try...catch block, the error that's caught is:
document.getElementById(...) is null
The same problem exists when you use textContent instead of innerHTML. I'm a little surprised that everybody is saying that this is how you're supposed to change the text of an element when it really doesn't suit that purpose very well. What's the right way to set this up?
p and h1 are not "empty elements", meaning they're not closed in the same tag that opens them (like img and br). If you write them like that, they're not valid tags and the browser will ignore them (which is why document.getElementById can't find them). Try this instead:
<html>
<head></head>
<body>
<h1 id="header"></h1>
<p id="p1"></p>
<script type="text/javascript">
document.getElementById("header").innerHTML = "header";
document.getElementById("p1").innerHTML = "p1";
</script>
</body>
</html>
Change your html to this :
<h1 id="header"></h1>
<p id="p1"> </p>
And try your JavaScript code now they will work, because they are not empty elements.
I think the main issue you are having is with the way you are setting up the closing tags like so: <h1 id="header"/> with / instead of a closing statement. This is incorrect and you need to close it like so: <h1 id="header"></h1> The same is true for the <p> tag and many others. There are some exceptions to this rule which you can find here:
http://www.w3schools.com/html/html_elements.asp
Here is an example fiddle with the actual result!
http://jsfiddle.net/nd3Dq/
I really cannot understand why this does not work. I've tried couple of tricks but I just don't get it.
<html>
<head>
<script type="text/javascript">
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
</script>
</head>
<body>
<div id="results">
hey there
</div>
</body>
</html>
This is working as you can see here:
http://jsfiddle.net/gHbss/
It's important that you put the JavaScript after your HTML div container.
The problem that you're facing is that the browser runs the JavaScript as it's encountered when rendering/processing the page. At this point it will alert() your message, but the relevant element, the #results div isn't present in the DOM, so nothing can be changed.
To address this, you can either place the script at the end of the page, just before the closing </body> tag, or run the code in the onload event of the body or window.
The script has to be placed after the div#results or executed onload, otherwise the element is still unknown when you try to access it.
You need to call this script in onload event
i.e
window.onload=function(){
//your code
}
<html>
<head>
<script type="text/javascript">
function onloadCall()
{
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
}
</script>
</head>
<body onload="onloadCall()">
<div id="results">
hey there
</div>
</body>
</html>
Hope the above snippet shows you the fix