How do I show myFunction content in myDiv
div? So show "Example"?
function myFunction() {
document.getElementById("demo").innerHTML = "Example!";
}
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
}
<div >
<p id="demo"></p>
</div>
CodePudding user response:
You can solve this just by using the getElementById
no need for a function.
document.getElementById("demo").innerHTML = "Example!";
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
}
<div >
<p id="demo"><p>
</div>
CodePudding user response:
This code:
<div >
<p> id="demo"</p>
</div>
Should be this:
<div >
<p id="demo"></p>
</div>
With the id
tag inside <p>
And this:
function myFunction() {
document.getElementById("demo").innerHTML = "Example!";
}
Should also get called since it is a function and not just the document.getElementById("demo").innerHTML = "Example!";
Example 1:
function myFunction() {
document.getElementById("demo").innerHTML = "Example!";
}
myFunction();
function myFunction() {
document.getElementById("demo").innerHTML = "Example!";
}
myFunction();
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
}
<div >
<p id="demo"></p>
</div>
Example 2:
document.getElementById("demo").innerHTML = "Example!";
document.getElementById("demo").innerHTML = "Example!";
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
}
<div >
<p id="demo"></p>
</div>
CodePudding user response:
Your function selects the element with id "demo"
, but there is no such element. You need to select your div
. You can do it by assigning it an id and then select that id. You can also select it via the class, using the getElementsByClassName
method, but since class is not unique, this method returns an array rather than a single element. Your div
will be the first item (index 0) in that array, in this case.
CodePudding user response:
I think you are not clear about the concept of html,CSS and js.myDiv is a CSS class.You can beatify the class in it.Whatever html tag uses that class will integrate the proper of .myDiv class. myFunction() is a js function if you use the demo id in your html tag and it will act according to your function defination.