Reputation: 23
I want my code to instead of creating two texts with my newly created span, i want it to say"Some text x2" and then x3 and so on.
Heres my code
<div>
<li id="myLi">
Some text (This is where i want my other text to be instead)
</li>
</div>
<td class="add" onmousedown="myFunction()">Add</td>
When i click the td, it adds to the li but when i click several times it just comes more text. I want it to say "Some text x2" instead.
function myFunction() {
var proc = document.createElement("SPAN");
var t = document.createTextNode("Some new text.");
proc.appendChild(t);
document.getElementById("myLi").appendChild(proc);
}
Thanks
Upvotes: 2
Views: 4530
Reputation: 5131
How about this piece?
var globalCounter = 1;
function myFunction(){
var current = document.getElementById("myLi");
current.innerHTML = "Some Text x"+globalCounter;
globalCounter++;
}
http://jsbin.com/munukadama/edit?html,js,output
Note you will be using global counter. If you want to avoid global conflicts, either come up with unique variable name, or encapsulate within a class as a private variable (see below).
function MyClass(){
var counter = 1;
this.update = function(){
var current = document.getElementById("myLi");
current.innerHTML = "Some Text x"+counter;
counter++;
};
}
var myInstance = new MyClass();
And then button will become:
<button onClick="myInstance.update()">Click me for Class!</button>
Upvotes: 1
Reputation: 3308
Here is a jQuery solution & a jsfiddle to test it out with:
HTML:
<ul>
<li id="myLi">
Some text (This is where i want my other text to be instead)
</li>
</ul>
<a href="#" class="add">Add</a>
JavaScript:
function myFunction() {
$('#myLi').html('<span>Some new text.</span>');
}
$('.add').on('click', myFunction);
Upvotes: 0
Reputation: 290
As Mike said, you can do this with an innerHTML. If I understand, what you want is :
var i =0;
function doStuff(){
var proc = "<span> my text instead x"+i + "</span>" ;
document.getElementById("myLi").innerHTML = proc;
i++;
}
<div>
<li id="myLi">
<p> something </p>
</li>
<div>
<button onclick="doStuff()"> CLICK ME </button>
Upvotes: 1