Find replace html using javascript - javascript

I've read a bunch of different posts and I can't figure out why this isn't working for me. Any help would be greatly appreciated. I'm sure it's something simple.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script type="text/javascript">
$("body").children().each(function() {
$(this).html($(this).html().replace(/®/g,"<sup>®</sup>"));
});
</script>
</head>
<body>
<div>HelloWorld®</div>
</body>
</html>

you must wait after page ready so add your function inside $(document).ready(function(){....}) or move your <script>...</script> tag as last element inside <body>...</body>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div>HelloWorld®</div>
<script type="text/javascript">
$("body").children().each(function() {
$(this).html($(this).html().replace(/®/g,"<sup>®</sup>"));
});
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("body").children().each(function() {
$(this).html($(this).html().replace(/®/g,"<sup>®</sup>"));
});
});
</script>
</head>
<body>
<div>HelloWorld®</div>
</body>
</html>

I have tested your code and it works for me. I output to the console the contents of the element before and after modifying them:
$("body").children().each(function() {
console.log($(this).html());
$(this).html($(this).html().replace(/®/g,"<sup>®</sup>"));
console.log($(this).html());
});
And the result is:
HelloWorld®
HelloWorld<sup>®</sup>
Check it here:
https://jsfiddle.net/m6kLgpj7/
Are you getting a different result? What is the problem you are observing?

To be honest I would probably just target the element by giving it a unique ID rather than iterate over every element in the body. However since that is the approach you asked about, this is how I would do it:
$(document).ready(function() {
$("body").children().each(function(idx, elem) {
var newHtml = $(elem).html().replace(/®/g, "<sup>®</sup>");
$(elem).html(newHtml);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Untitled Document</title>
<body>
<div>HelloWorld®</div>
</body>
I think it's more clear when you use the second parameter that the jQuery each method provides (the element), rather than using 'this' all over the place....just my personal preference.
Also, take note of the document ready method i placed the rest of the script in to ensure. This ensures the script does not manipulate the DOM until the DOM is ready.

Related

Access variable from iframe without editing iframe page

I want to access variable from iframe without editing iframeContent.html page. I don't know why alert window still shows 'undefined'
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var iframe0=0;
var iframe0document=0;
var inputIframe=0;
function getIframeText() {
var iframe0 = document.getElementById("iframe123");
var iframe0document=iframe0.contentDocument||iframe0.contentWindow.document;
var inputIframe = iframe0document.getElementById("wynik2");
alert(inputIframe.value);
};
</script>
</head>
<body>
<div>
<button onclick="getIframeText()">get iframe text</button>
<iframe id="iframe123" src="iframeContent.html" >
</div>
</body>
</html>
iframeContent.html:
<html>
<head>
<title>IFrame Child Example</title>
<script type="text/javascript">
var asd="12";
</script>
</head>
<body>
<div id="wynik2"></div>
<script type="text/javascript">
document.getElementById("wynik2").innerHTML=asd;
</script>
</body>
</html>
Frame on parent page looks good (shows number 12). I'm testing my page on Chrome but through command window typing 'allow file access from files'. So this isn't problem. Global variables are also set (am I doing it right?) so I don't know why is still udefined.
use inputIframe.innerText instead of inputIframe.value . "wynik2" is a div, right? cheers! :)

Cannot set property 'innerHTML' of null

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?
I thought I understood innerHTML and had it working before.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</head>
<body>
<div id="hello"></div>
</body>
</html>
You have to place the hello div before the script, so that it exists when the script is loaded.
Let us first try to understand the root cause as to why it is happening in first place.
Why do I get an error or Uncaught TypeError: Cannot set property
'innerHTML' of null?
The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the script tags (present in head section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded. The scripts present in head tag are trying to access an element having id hello even before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.
How can you make it work as before?
You want to show the hi message on the page as soon as the user lands on your page for the first time. So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the hello id element is accessible/available. It is achievable in two ways:
Reorder your scripts: This way your scripts get fired only after the DOM containing your hello id element is already loaded. You can achieve it by simply moving the script tag after all the DOM elements i.e. at the bottom where body tag is ending. Since rendering happens from top to bottom so your scripts get executed in the end and you face no error.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
Use event hooking: Browser's rendering engine provides an event based hook through window.onload event which gives you the hint that browser has finished loading the DOM. So by the time when this event gets fired, you can be rest assured that your element with id hello already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail. So you do something like below code snippet. Please note that in this case, your script works even though it is present at the top of your HTML document inside the head tag.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
<script type ="text/javascript">
window.onload = function() {
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
}
</script>
</head>
<body>
<div id="hello"></div>
</body>
</html>
You could tell javascript to perform the action "onload"... Try with this:
<script type ="text/javascript">
window.onload = function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
Just put your JS in window.onload
window.onload = function() {
what();
function what() {
document.getElementById('hello').innerHTML = 'hi';
};
}
The JavaScript part needs to run once the page is loaded, therefore it is advised to place JavaScript script at the end of the body tag.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
Javascript looks good. Try to run it after the the div has loaded. Try to run only when the document is ready. $(document).ready in jquery.
Here Is my snippet try it. I hope it will helpfull for u.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = '<p>hi</p>';
};
</script>
</body>
</html>
You could try using the setTimeout method to make sure your html loads first.
The root cause is: HTML on a page have to loaded before javascript code.
Resolving in 2 ways:
1) Allow HTML load before the js code.
<script type ="text/javascript">
window.onload = function what(){
document.getElementById('hello').innerHTML = 'hi';
}
</script>
//or set time out like this:
<script type ="text/javascript">
setTimeout(function(){
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
}, 50);
//NOTE: 50 is milisecond.
</script>
2) Move js code under HTML code
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
I have had the same problem and it turns out that the null error was because I had not saved the html I was working with.
If the element referred to has not been saved once the page is loaded is 'null', because the document does not contain it at the time of load. Using window.onload also helps debugging.
I hope this was useful to you.
This error can appear even if you load your script after the html render is finished. In this given example your code
<div id="hello"></div>
has no value inside the div. So the error is raised, because there is no value to change inside. It should have been
<div id="hello">Some random text to change</div>
then.
Add jquery into < head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
Use $document.ready() : the code can be in < head> or in a separate file like main.js
1) using js in same file (add this in the < head>):
<script>
$( document ).ready(function() {
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
});
</script>
2) using some other file like main.js (add this in the < head>):
<script type="text/javascript" src="/path/to/main.js" charset="utf-8"></script>
and add the code in main.js file :)
You need to change div into p. Technically innerHTML means it is inside the <??? id=""></???> part.
Change:
<div id="hello"></div>
into
<p id="hello"></p>
Doing:
document.getElementById('hello').innerHTML = 'hi';
will turn
<div id="hello"></div> into this <div id="hello">hi</div>
which actually does not make sense.
You can also try to change:
document.getElementById('hello').innerHTML = 'hi';
into this
document.getElementById('hello').innerHTML='<p> hi </p> ';
to make it work.
The error is self-explaining it is not getting the HTML tag in which You want to set the Data So make tag available to JS then only You can set Data to that.
No doubt, most of the answers here are correct, but you can also do this:
document.addEventListener('DOMContentLoaded', function what() {
document.getElementById('hello').innerHTML = 'hi';
});
There are different possible cause as discussed would just like to add this for someone who might have the same issue as mine.
In my case I had a missing close div as shown below
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div> //I am an open div
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
Missing a close div can result in disorganization of the transversal from child to parent or parent to child hence resulting in an error when you try to access an element in the DOM
Let the DOM load. To do something in the DOM you have to Load it first. In your case You have to load the <div> tag first. then you have something to modify. if you load the js first then that function is looking your HTML to do what you asked to do, but when that time your HTML is loading and your function cant find the HTML. So you can put the script in the bottom of the page. inside <body> tag then the function can access the <div> Because DOM is already loaded the time you hit the script.
I have moved my <script> tag below the <body> tag. Let’s try
<body>
<p>The time is <span id="time"></span>.</p>
</body>
<script>
// Allways keep script at end for date and time object //
var d = new Date();
document.getElementById("time").innerHTML = d;
</script>
This happened to me when using Django template tags on an if-check to see if there was a value available for a field - if no value I removed everything associated with the value from the page to keep things neat The only problem was the content I removed included the div and id I was trying to work with! If there was a value present there was no issue as the div that contained the id I was working with was present. If there was no value I received the error. Once it hit me that's what was going on then easy fix to just add the div in there if the if-check is false.
Before
{% if model.value %}
<div id='my-id'>{{model.value}}</div>
{% endif %}
After
{% if model.value %}
<div>{{model.value}}</div>
{% else %}
<div id='my-id'></div>
{% endif %}

Getting a Simple YUI Example to Work

I'm reading over the "Getting Started" part of YUI and I can't get the basics to work. What am I doing wrong in this code sample that won't allow this contentNode to print? When I try to view it in the browser, nothing happens.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>YUI</title>
<script src="http://yui.yahooapis.com/3.7.3/build/yui/yui-min.js"></script>
<script>
YUI().use('node', function (Y) {
// Create DOM nodes.
var contentNode = Y.Node.create('<div>');
contentNode.setHTML('<p>Node makes it easy to add content.</p>');
});
</script>
</head>
<body>
</body>
</html>
This is just something that might not have been clear with the "Getting Started" section of YUI, but Y.Node.create makes a Node object, but doesn't attach it to the DOM yet. If you want to do that, just add one more line to your code to do so (such as append/prepend/insert/etc.):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>YUI</title>
<script src="http://yui.yahooapis.com/3.7.3/build/yui/yui-min.js"></script>
<script>
YUI().use('node', function (Y) {
// Create DOM nodes.
var contentNode = Y.Node.create('<div>');
contentNode.setHTML('<p>Node makes it easy to add content.</p>');
// Attaches created node to the DOM
Y.one('body').append(contentNode);
});
</script>
</head>
<body>
</body>
</html>

What is the difference between these two jQuery usage

Im a jquery starter so if its a wrong one forgive me :)
I just want to know why placing the content at different positions made this script working, although to my best i think script to kept in head section of the document. Please explain the concept.
Working Code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example 2</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>
</p>
<script type="text/javascript">
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
</script>
</body>
</html>
Not Working
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example 2</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
</script>
</head>
<body>
<p>
</p>
</body>
</html>
In the second instance the code is executed before the <p> has been parsed into the DOM tree, so while it still works there's nowhere to put the output text into. In other words, jQuery("p") matches no element so .html() "does nothing".
You can fix this by either waiting for the DOM to be fully parsed:
jQuery(function() {
jQuery("p").html(...);
});
or by using an output mechanism that does not depend on the <p> existing, such as alert() or console.log().
Well, it seems that your browser firstly load <head> section thus in second example there is no p element then.
In both cases you should wrap your code in $(function(){ ... }).
If you place your script before the <body> element, it is executed before the DOM tree is loaded/parsed. The <p> element does therefore not exist and cannot be found. You can:
Place the script after the <body> tag (like in your first example)
or you can call your function after the ready event has been fired:
$(document).ready(function() {
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
});

how to use sizzle.js separate

I downloaded sizzle.js from https://github.com/jquery/sizzle
my code is:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="sizzle.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload=load;
function load(){
alert(Sizzle("#test"));
alert(Sizzle("#test").innerHTML);
}
</script>
</head>
<body>
<div id="test">abc</div>
</body>
</html>
but alert "[object]", "undefined", please tell me what's wrong with my code?
The Sizzle() function returns an array of matched elements. So if you know there'll be exactly one matching element (which there should be if you're selecting by id) try:
alert(Sizzle("#test")[0].innerHTML);
You've did a slight mistake it returns NodeList not a single Node.
The NodeList is like an array but used for storing Nodes. You may probably want to use the first one.
// this is how you do it
alert( Sizzle('#test')[0].innerHTML );

Categories