<div id="container">
<h1>Hello, DOM!</h1>
<p>This is some fine fruit:</p>
<ul class="listy">
<li>Apples</li>
<li class="second">Pears</li>
<li>Cherries</li>
</ul>
</div>
CSS
<!DOCTYPE html>
<html>
<head>
<style>
p#demo {
color: red;
}
</Style>
</head>
<body>
<p id="demo"> enter car name here </p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
</style>
</body>
</html>
JavaScript
/**
* We can drop in straight html by using innerHTML property
*/
var htmlFragment = "<a href='http://www.google.com'>Search</a>";
var pEl = document.getElementsByTagName("p")[0];
pEl.innerHTML += " " + htmlFragment;
/**
* We can create elements through the DOM
*/
// create the element
var newLi1 = document.createElement('li');
// give it some text
var newLiText = document.createTextNode('Watermelon');
newLi1.appendChild(newLiText);
// determine position for insertion
var ulElement = document.querySelector(".listy");
// insert it
ulElement.appendChild(newLi1);
/**
* More insertion
*/
var newLi2 = document.createElement('li');
newLi2.innerHTML = "Grapes";
ulElement.insertBefore(newLi2, newLi1);
/**
* Warning: These will MOVE elements that already exist
*/
/*
var h1El = document.getElementsByTagName('h1')[0];
ulElement.appendChild(h1El);
*/
/**
* Replacing
*/
var newLi3 = document.createElement('li');
newLi3.innerHTML = "Peaches";
ulElement.replaceChild(newLi3, newLi1);
/**
* Removing elements
*/
// get a reference node-to-be-removed
var liToRemove = document.querySelector(".second");
// and remove it through the parent
liToRemove.parentNode.removeChild(liToRemove);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.