Change element text without jQuery? - javascript

I am trying to change the contents of a div without using jQuery. I want to select the div by id or class.
Ive managed to get append to work:
function appendHtml(targetC, htmldata) {
var theDiv = document.getElementById(targetC);
var newNode = document.createElement('div');
newNode.innerHTML = htmldata;
theDiv.appendChild(newNode)
}
But cant figure out how to change text of one..
Any ideas?

see this fiddle for a basic sample
<html>
<head>
<script>
function bold(targetC) {
var theDiv = document.getElementById(targetC);
theDiv.innerHTML = '<b>' + theDiv.innerHTML + '</b>';
}
</script>
</head>
<body onload='bold("message")'>
<div>Hello, World!</div>
<div id="message">What a nice day!</div>
</body>
</html>

Edited:
<div id="foo">old text</div>
The JS code:
function appendHtml(targetC, htmldata) {
var theDiv = document.getElementById(targetC);
theDiv.innerHTML = htmldata;
}
appendHtml('foo', 'new text');
Here is a fiddle: http://jsfiddle.net/7QjcB/

simply change the html of a div by using innerHTML
var anyDiv = document.getElementById(targetID);
html = "content";
anydiv.innerHTML(html);
as a variation of your provided function:
function changeHtml(targetC, htmldata) {
var theDiv = document.getElementById(targetC);
theDIV.innerHTML = htmldata;
}

Here is a fiddle that might answer your question. All I changed was getting the element before and then passing it in.
function appendHtml(targetC, htmldata) {
var newNode = document.createElement('div');
newNode.innerHTML = htmldata;
targetC.appendChild(newNode);
}
var getDiv = document.getElementById("testing");

Related

appendChild where javascript is included

I want to be able to create a JavaScript element where the script is included.
Example:
<script src='addDiv.js'></script>
The addDiv.js simply adds a customized div as below:
var element = document.createElement("div");
element.setAttribute("id", "myspecialdiv");
document.body.appendChild(element);
I want to add this div wherever this script is included instead of at the end of body. Is there a way to achieve this ?
Thanks
In most modern browsers you can use document.currentScript;
<script>
function replaceScript(el, text) {
let p = document.createElement('p')
p.innerText = text;
el.replaceWith(p);
}
</script>
<script>
replaceScript(document.currentScript, 'Test 1');
</script>
<script>
replaceScript(document.currentScript, 'Test 2');
</script>

Remove wrapper div from document.createElement

I've been stuck on this for the longest time and it's driving me nuts. I've tried a dozen different methods and can't figure out how to get it to work. Any help would be appreciated!! Thanks
Here's my code:
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
//My current method. this method works but creates another wrapper div. I need a way to remove the wrapper div or a different method altogether without any wrapper divs.
var z = document.createElement('div');
z.innerHTML = item;
element.appendChild(z);
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
element.innerHTML = item;
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
As you've tagged with jQuery, you can create the element as follow:
$(item);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function runScript() {
var item = "<div>test1</div><div>test2</div>";
$(document.currentScript.parentElement).append($(item));
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
You can use the insertAdjacentHTML method.
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
element.insertAdjacentHTML('beforeend', item);
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>
Or use a template instead of a DIV.
<script>
function runScript() {
//get parent of script element
var element = document.currentScript.parentElement;
//my html string that needs to be inserted inside the original div
var item = "<div>test1</div><div>test2</div>";
var z = document.createElement('template');
z.innerHTML = item;
element.appendChild(z.content);
}
</script>
<div id="main-wrapper">
<script>
runScript();
</script>
</div>

Can't find DIV in JS

I'm creating a webPage, I need to get an element by ID, but when I try to do it, the element returned is a null object.
I think because the div that I want to get is added in the HTML code when I press a button, but my JS code is compiled when the page is loaded, so JS can't find the div... How can I select my div with JS?
<html><head><script>
function getDiv(){
var div = document.getElementById('div_name');
div.innerHTML = "SOMETHING"; //div is null
//<div id="div_name"></div> isn't added when the page is loaded
}
function addDiv()
{
var iDiv = document.createElement('div');
iDiv.id = 'div_name';
document.getElementsByTagName('body')[0].appendChild(iDiv);
}
</script></head>
<body>
<button onClick="getDiv()">GETDIV</button>
<!-- Pretend that with this button I add the div with 'div_name' in my HTML
page -->
<button onClick="addDiv()">ADDDIV</button>
</body></html>
Refer below code :-
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function addDiv(){
var div = document.getElementById('div_name');
var isDivPresent = (div && (div !== null ));
if(isDivPresent){
return;
}
var createDiv = document.createElement("div");
createDiv.setAttribute("id", "div_name");
createDiv.style.backgroundColor = "lightblue";
createDiv.style.width='250px';
createDiv.style.height='300px';
document.getElementsByTagName('body')[0].appendChild(createDiv);
}
function getDiv(){
var div = document.getElementById('div_name');
var isDivPresent = (div && (div !== null ));
if(!isDivPresent) {
addDiv();
getDiv();
}else {
div.innerHTML = "SOMETHING";
}
}
</script>
</head>
<body>
<button onClick="addDiv()">ADDDIV</button>
<button onClick="getDiv()">GETDIV</button>
</body>
</html>
function getDiv(){
var div = document.getElementById('div_name');
div.innerHTML = "SOMETHING"; //div is null
}
function addDiv(){
if(!document.getElementById('div_name')){
var div = document.createElement("div");
div.id = 'div_name';
div.innerHTML = "Added Through add div";
document.body.appendChild(div);
}
}
<button onClick="getDiv()">GETDIV</button>
<button onClick="addDiv()">ADDDIV</button>
here is a code that works as you whish. The main differences is :
I used onclick as attribute name instead of onClick
function addDiv() {
var div = document.createElement('div');
div.id = 'div_name';
document.body.appendChild(div);
div.innerHTML = 'initial content';
}
function updateDiv() {
var div = document.getElementById('div_name');
div.innerHTML = 'new content';
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<button onclick="addDiv();">add div</button>
<button onclick="updateDiv();">replace div content</button>
</body>
</html>
If you click the GETDIV button without clicking the ADDDIV button first, then the div you're looking for isn't anywhere in the document body. So I would change the getDiv() like so:
function getDiv(){
var div = document.getElementById('div_name');
if(!div) { // if div is not added yet, then add it
addDiv();
}
div.innerHTML = "SOMETHING"; //div is null
}

How To Create And Assign And Onclick Element To Another Element Created In JS

So, I am trying to make an element and then assign an onclick to it through JS.
Here is my code so far:
HTML
<div id = "Programs" onclick = "Cpb()">Programs</div>
JS
function Cpb() {
document.getElementById("AllBody").innerHTML = "";
var rh = document.createElement("h2");
var rht = document.createTextNode("Recent Programs");
rh.id = "Recentt";
var rh1 = document.createElement("h4");
var rh1t = document.createTextNode("test");
rh1t.onclick = window.open('website');
rh1.appendChild(rh1t);
rh.appendChild(rht);
}
So does anybody know how I can do this?
This javascript worked for me:
let h4Node = document.createElement("H4");
h4Node.innerHTML = "4th Header";
h4Node.onclick = function (){
alert('Oi!');
};
document.getElementById("demo").appendChild(h4Node);
Html:
<div class="demo"></div>
It will put an h4 element with an onclick event listener inside the demo div.
I think you want addEventListener.
Example:
rh1t.addEventListener('click', myHandlerFunction);
function myHandlerFunction () {
// ...
}
You can continue using onclick as you have in your code. But you'll need to do as I've done above and assign a function reference to it. Like this:
rh1t.onclick = myHandlerFunction;
function myHandlerFunction () {
window.open('website');
}

onmouseout event not working with h1 tags

I am trying onmouseout and onmouseover events. Below code is working fine if i remove tags, what is confusing me is , with tags, only mouseover is firing and not mouseout. Please guide what i am doing wrong.
<!DOCTYPE html>
<html>
<body>
<div onmouseout="mouseout();" onmouseover="mouseover();" id="test"><h1> Mouse </h1> </div>
<div id="count"> </div>
<div id="count2"> </div>
<script>
var textonout = "<h1>Mouse out</h1>";
var count =0;
var out = 0;
var textonover = "<h1>Mouse Over</h1>";
function mouseout() {
document.getElementById("test").innerHTML = textonout;
document.getElementById("count2").innerHTML = out++;
}
function mouseover() {
document.getElementById("test").innerHTML = textonover;
document.getElementById("count").innerHTML = count++;
}
</script>
</body>
</html>
EDIT: Ok i think i understand my own question. In my case, onmouseout event doesnt fire if i have nested tags. I have tried the same code just replacing h1 tag with a div tag. I tried several combination (using span etc) as soon as i introduce any tag inside my first div, onmouseout stops working.
Can someebody guide me what is the issue ? i am not asking for the fix, i just want to understand the reason of this error.
EDIT(2). Another update, if i add the following lines, now the onmouseout event is triggering.
function mouseover() {
document.getElementById("test").innerHTML = textonover **+ count**;
document.getElementById("count").innerHTML = count++;
DEMO
Uncaught ReferenceError: mouseout is not defined
You had this error in your console. I admit, I prefer to seperate js and html. Call your events in your JS.
Additionally, you don't need to recreate an h1 everytime you want to change the text. Just add an id to your h1, and replace the text inside of it.
HTML:
<div id="test">
<h1 id="h1"> Mouse </h1>
</div>
<div id="count"></div>
<div id="count2"></div>
Javascript:
var h1 = document.getElementById('h1');
textonout = "Mouse out";
var count = 0;
var out = 0;
var textonover = "Mouse Over";
var test = document.getElementById("test");
test.onmouseout = mouseout;
test.onmouseover = mouseover;
function mouseout() {
h1.innerHTML = textonout;
document.getElementById("count2").innerHTML = out++;
}
function mouseover() {
h1.innerHTML = textonover;
document.getElementById("count").innerHTML = count++;
}
Follow this , it work perfect.
<!DOCTYPE html>
<html>
<body>
<h1 id="test"> Mouse </h1>
<div id="count"> </div>
<div id="count2"> </div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
var textonout = "Mouse out";
var count =0;
var out = 0;
var textonover = "Mouse Over";
$("h1").mouseover(function(){
$("h1").css("background-color","yellow");
document.getElementById("count").innerHTML = count++;
document.getElementById("test").innerHTML = textonover;
});
$("h1").mouseout(function(){
$("h1").css("background-color","lightgray");
document.getElementById("test").innerHTML = textonout;
document.getElementById("count2").innerHTML = out++;
});
});
</script>
</body>
</html>

Categories

Resources