Is there an easy way to change this from appendChild to replaceChild?
This of course continuously adds more ele. Also for some reason it doesn't put the value inside the DIV or SPAN, seems to put below it.
var para = document.createElement("P");
var total = document.createTextNode(parseFloat((subT + tax).toFixed(2))) ;
para.appendChild(total);
document.getElementById("total_id").appendChild(para);
Its updating this:
<div class="prod_totals">Order Total: $<span id="total_id"></span></div>
you can simply use innerHTML instead of appendChild
document.getElementById("total_id").innerHTML = parseFloat((subT + tax).toFixed(2));
Because you're not inserting any user input values inside the total_id element and also as far as the question mentions, its data is not later passed to the server I think you'll be safe using the innerHTML here. But if for any reasons you'd still like to use replaceChild you could do it like this:
var para = document.createElement("P");
var total = document.createTextNode(parseFloat((subT + tax).toFixed(2))) ;
para.appendChild(total);
var existingText=document.getElementById("total_id").querySelector('p');
if(existingText){
document.getElementById("total_id").replaceChild(existingText, para);
}
else{
document.getElementById("total_id").appendChild(para);
}
There's no need to use .replaceChild here, you can simply check if the element was already created before trying to update it.
Note that you were trying to insert a p element inside a span which is wrong and is not valid HTML markup, you can see in the span documentation that its possible content is only Phrasing content, so you better use another span.
This is how should be your code:
var para = document.querySelector("#total_id span");
if (!para || para.length == 0) {
para = document.createElement("span");
}
var total = parseFloat((subT + tax).toFixed(2));
para.innerText = total;
document.getElementById("total_id").appendChild(para);
And here's a Demo:
var para = document.querySelector("#total_id span");
if (!para || para.length == 0) {
para = document.createElement("span");
}
var total = new Date();
para.innerText = total;
document.getElementById("total_id").appendChild(para);
<div class="prod_totals">Order Total: $<span id="total_id"></span></div>
Related
Is this possible? Or is there a way to tack on and ID to an existing div?
This is my code. I can't get the code to work using classes, but I found when I used getElementById and changed the div to an ID, that it did. But I have a ton of already posted stuff so it would take forever to go through all those posts and change it manually to an ID.
Can I incorperate JQuery in this and still have it work? I tried that with something I stumbled across but it didn't work so I removed it. I don't remember what it is now though. :S
<div id="imdb" class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnum = document.getElementsByClassName("imdb");
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnum + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
window.onload = imdbdiv();
</script>
Can anyone help. I cannot for the life of me figure this out.
JsFiddle
Your problem was, you were appending the collection returned by document.getElementsByClassName instead of looping through the elements in the collection. You can verify this by looking at the href property of the link in your jsFiddle. You must loop through the values, then access the data in their innerHTML property.
You can use document.querySelectorAll to get a list of all elements matching a certain CSS selector, in your case .imdb. This is more flexible, in case you want to select elements with more than one class. I've pasted the code from the updated jsFiddle below.
function imdbdiv() {
var imdbMain = "http://www.imdb.com/title/",
end = "/#overview-top",
imdbValueDivs = document.querySelectorAll('.imdb'),
length = imdbValueDivs.length,
// Iterator values
i,
newDiv,
newLink;
// Loop over all of your link value containers
for (i = 0; i < length; i++) {
// Create the container
newDiv = document.createElement('div');
// Create the new link
newLink = document.createElement('a');
newLink.href = imdbMain + imdbValueDivs[i].innerHTML + end;
newLink.innerHTML = "My favorite film";
// Add the link to the container,
// and add the container to the body
newDiv.appendChild(newLink);
document.body.appendChild(newDiv);
}
}
window.onload = imdbdiv();
If you have many such divs on your page, then it could be like this:
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnums = document.getElementsByClassName("imdb");
for (var i =0; i < idnums.length; i++) {
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnums[i].innerText + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
}
window.onload = imdbdiv();
</script>
See jsfiddle
UPDATE:
The following string was incorrect:
window.onload = imdbdiv;
Okay, so your question is a little bit unclear.
The way I understood your question is that you have a whole bunch of div elements with class attribute and what you want is to simply copy the class value to the id attribute of the div elements.
If that's correct then try something like this with jquery:
<script>
$(document).ready(function(){
$(".imdb").each(function(imdbDiv){
var classValue = imdbDiv.attr("class");
imdbDiv.attr("id", classValue);
});
});
</script>
I've been working on a form were i can make extra inputfields and selectfields thanks to this site! Al those fields get unique id (3011, 3012, 3013 to a max of 3019) and (rc1, rc2 etc.)
with a removal link.
var i = 2;
var limit = 10;
function createInput () {
if (i == limit) {
alert("You have reached the limit of adding " + i + " inputs");
}
else
var field_area = document.getElementById('301X')
var div = document.createElement("div");
div.id = 'SA '+i;
var input = document.createElement("input");
div.innerHTML = '301'+i ;
input.id = '301'+i;
input.name = '3011';
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
input.value = "";
input.size = '80';
var rcnode = document.getElementById("rc1") // bepaal var van de select menu id relcode
var rcclone = rcnode.cloneNode(true); // bepaal var van de clone van de select
rcclone.id = 'rc'+i; // het nummeren van id clone
div.appendChild(input);
div.appendChild(rcclone);
field_area.appendChild(div);
and it works fine (would not surprise me that it can be beter) Now I want to catch the values. I succeed to cath it from one value with this script:
var x = 1;
function catchInput () {
var said = '301'+x;
var rcid = 'rc'+x;
var Valsaid = document.getElementById(said).value;
var Valrcid = document.getElementById(rcid).value;
alert (said + ' ' + Valsaid + Valrcid);
}
but I want to catch them all. I have been playing around with arrays and the for-loop but I can't figure it out. Any help, point in the right direction much appreciated.
Herman
There are several possibilities :
1) prefix your id's with a common string, then use jQuery (for example) to find all elements with id's starting with this prefix : $('[id^=yourPrefix]')
2) if you want to stick with POJS, "group" these dynamically generated elements by assigning a common class to them. you can then use getElementsByClassName() , which is not available in all browsers though (actually only a problem with IE <= 8)
3) still if you want to stick with POJS but need extended browser support, you can prefix your id's with a common string, then loop on your elements (maybe restricting the set using getElementsByTagName()) and test if the id string starts with this prefix using indexOf() , for example (that's most probably how jQuery implements this functionality)
Hope this helps...
I have to make text bold if I click on a button using nodes and createElement but I don't really know how...
html (This is the text I want to make bold):
<p id="textalt">Dies ist ein Text in einem P-Tag</p>
javascript:
function fettmachen(){
var neuB = document.createElement("b");
document.getElementById("textneu").insertBefore(neuB, document.getElementById("textneu").nextSibling);
}
I don't know how it works.
"I have to do it with nodes and createElement"
function fettmachen(){
// create the "b" element
var neuB = document.createElement("b");
// fetch the "textneu" element by ID
var textneu = document.getElementById("textneu");
// append the firstChild of "nextneu" to the "neuB"
neuB.appendChild(textneu.firstChild);
// append the "neuB" to the "nextneu"
nextneu.appendChild(neuB);
}
I suggest, instead of adding new tags, just use CSS, and add a class to the element.
CSS:
.boldText{
font-weight: bold;
}
JavaScript:
function fettmachen(){
document.getElementById("textalt").className += ' boldText';
}
I'd just put a style on the <p> tag on the button press. Maybe something like...
function fettmachen(){
var neuB = document.getElementById("textalt");
neuB.style.fontWeight = "bold";
}
Well, you could use the following code. It's longer and could be condensed - I find it clearer to read, personally.
function fettmachen()
{
var pElem = document.getElementById('textAlt');
var text = pElem.innerHTML;
var bElem = document.createElement('b');
bElem.innerHTML = text;
pElem.innerHTML = '';
pElem.appendChild(bElem);
}
This is how you make the text bold
function fettmachen(){
var p = document.getElementById("textneu");
p.style.fontWeight = "bold;"
}
If you have to use js for some reason for instance you need to only bold certain words maybe, and don't have access to the style sheet here you go. Otherwise use what Rocket has suggested.
Seriously only use a solution like this if at some point you will need to only bold certain words, or groups of words within an element.
function fettmachen(){
var neuB = document.createElement("b"),
textEl = document.getElementById("textalt"),
text = textEl.textContent;
neuB.textContent = text;
textEl.textContent = "";
textEl.appendChild(neuB);
}
Live Demo
And to unbold.
function unbold(){
var textEl = document.getElementById("textalt"),
boldEls = textEl.getElementsByTagName("b"),
text = "";
for(var i = 0; i < boldEls.length; i++){
text+=boldEls[i].textContent;
textEl.removeChild(boldEls[i]);
}
textEl.textContent = text;
}
Live Demo 2
I have been strugling with this for a while and I am sure there is a simple answer to this. What happens is I remove a div called "payment" then dynamicaly create it again so I can add to it. That then gets repeated as the infomation that needs to be added to it changes.
I have mangaged to get this so far.
function clearPage()
{
var d = document.getElementById("contain");
var d_nested = document.getElementById("payment");
var deleteNode = d.removeChild(d_nested);
}
function createPayment()
{
payment = document.createElement("div");
payment.id = "mine";
document.getElementById("contain").appendChild(payment);
}
function printOnPage()
{
var x = names.length;
for( var i = 0 ; i < x ; i++ )
{
var para = document.createElement("p");
var paymentDiv = document.getElementById("payment");
paymentDiv.appendChild(para);
var txtName = document.createTextNode("Item: ");
para.appendChild(txtName);
var txtNameArray = document.createTextNode(names[i]);
para.appendChild(txtNameArray);
var txtQty = document.createTextNode(" Qty: ");
para.appendChild(txtQty);
var txtQtyArray = document.createTextNode(qty[i]);
para.appendChild(txtQtyArray);
var txtCost = document.createTextNode(" Cost: ");
para.appendChild(txtCost);
var txtCostArray = document.createTextNode(prices[i]);
para.appendChild(txtCostArray);
}
}
Related HTML
<div id="contain">
<p>Payment</p>
<div id="payment">
<br />
</div>
</div>
It needs the ID of payment for both my CSS rules and for my creating the text that goes in it.
This is the error I get in FireFox
Error: paymentDiv is null Source File:
http://itsuite.it.brighton.ac.uk/ks339/sem2/javascript/js.js Line: 76
Hope someone can provide some insight in to this and please tell me if I am completly off!
Thanks
Edit: Is it easior to clear the div rather than delete it, how would I go about doing such a thing?
In create_payment(), you set the ID to 'mine'. Shouldn't it be 'payment'?
I do not understand your requirements very well, but anyway you cannot create multiple items in the page using the same id attribute, if you want to duplicate an item and still have control over it, you should be using class instead.
Try switching your code into jquery it will be cleaner and easier to understand for you & me.
Your problem is the fact that in createPayment() you're setting the id to 'mine':
payment.id = "mine";
while later on in printOnPage() you're looking for the element using id 'payment':
var paymentDiv = document.getElementById("payment");
As you mention in your edit, it is far easier just to clear the div than to remove it, specially if you still need it later.
To clear a DIV-block just set it's content to empty:
document.getElementById('payment').innerHTML = "";
I hope you find a solution! Good luck!
I am trying to see how to find a tag that was added dynamically within a table as so:
ParentTag= document.getElementById('parentdiv');
var newTag = document.createElement('div');
newTag.innerHTML="<span class="ImNew"></span>"
ParentTag.appendChild(newTag);
How will I be able to find that tag in javascript, not leaning towards using jquery so no live recommendations please.. Trying to find that new tag in strictly javascript.
The tag I am referring to is the span tag
You could give your new tag an ID when you create it:
ParentTag= document.getElementById('parentdiv');
var newTag = document.createElement('div');
newTag.setAttribute('id','myNewID');
newTag.innerHTML="<span class="ImNew"></span>"
ParentTag.appendChild(newTag);
Then later, just use that ID to find it:
var newTag = document.getElementById('myNewID');
That depends on what other elements exist in the element. You can for example get all span tags in the element and filter out the ones with a specific class name:
var parentTag = document.getElementById('parentdiv');
var spans = parentTag.getElementsByTagname('SPAN');
var filtered = [];
for (var i=0; i<spans.length; i++) {
if (spans[i].className === 'ImNew') filtered.push(spans[i]);
}
If there is only one span tag with that class name in the element, the filtered array now cotnains a reference to that element.
As others have mentioned, why not just keep track of it or give it an id if you're going to need it later?
But anyway, this is how you could do a manual search (searching from back to front as you're adding the new items to the end).
var parent = document.getElementById("parentdiv")
for (var i = parent.childNodes.length - 1; i >= 0; i--)
{
var el = parent.childNodes[i];
if (el.nodeType == 1 &&
el.nodeName.toLowerCase() == "div" &&
el.firstChild &&
el.firstChild.nodeName.toLowerCase() == "span" &&
el.firstChild.className = "ImNew")
{
// el.firstChild is what you want
}
}