Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am having an issue making a div a child of another div. I would like to learn how to do this in javascript.
I would like to essentially create this:
<body>
<div id = "graph">
<div id "data">
</div>
</div>
</body>
By using javascript. The end goal is to create many of these over and over again.
Here is the code I have so far:
var graph = document.createElement('div');
graph.id = "graph";
document.body.appendChild(graph);
var barWrapper = document.createElement('div');
barWrapper.id = "data";
The above works with no error. When I add:
document.getElementbyId("graph").appendChild("data");
I get "Uncaught Type Error: Undefined is not a function".
From my research this seems to be everyone's suggestion. Also, the appendChild function seems to be complete to my knowledge. What am I missing? Thank you in advance!!
Your problem (which is causing your type error) is you're attempting to append a string, not a reference to the child element itself.
var parent = document.createElement("div");
parent.id = "graph";
var child = document.createElement("div");
child.id = "data";
parent.appendChild(child);
You should be appending an object just like you were doing with body.
var parent = document.getElementById("graph");
parent.appendChild(barWrapper);
Edit:
You also dont need to call getElementById here. You should be able to append the child to parent then append the parent to body. Like this:
var graph = document.createElement('div');
graph.id = "graph";
var barWrapper = document.createElement('div');
barWrapper.id = "data";
graph.appendChild(barWrapper);
document.body.appendChild(graph);
The error is beign caused by the typo, it should be getElementById
document.getElementbyId("graph")
>TypeError: undefined is not a function
when you fix that and execute the code you will get
document.getElementById("graph").appendChild("data")
>NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
this is because you are trying to append a string and not an actual html node. you will need to grab the element first as well
document.getElementById("graph").appendChild(document.getElementById("data"));
Since you already have references to both these objects a cleaner solution would be
grap.appendChild(barWrapper);
There are a couple problems
document.getElementbyId("graph") should be document.getElementById("graph")
.appendChild("data") should be .appendChild(bargraph)
This JS works:
var graph = document.createElement('div');
graph.id = "graph";
document.body.appendChild(graph);
var barWrapper = document.createElement('div');
barWrapper.id = "data";
document.getElementById("graph").appendChild(barWrapper);
Fiddle here: http://jsfiddle.net/hatvjete/
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to replace <p>Coding everybody</p> into <p>Hello world</p> in HTML with JavaScript.
For example, it would change the word "Coding everybody" to "Hello world".
EDIT: I'm trying to make and apply the script to a website BY USING A JAVASCRIPT APPLYER (TAMPERMONKEY)
Any ideas?
You'll need a way of 'selecting' the element you want to change.
You could add an ID;
<p id="myParagraph">Coding everybody</p>
Then, with Javascript;
const element = document.querySelector('#myParagraph');
element.innerHTML = 'Hello World';
if you don't know where this paragraph is or how to select it then you could select all paragraphs and find the one with the text that you are looking for.
If it's found, update the textContent property.
const paragraphs = document.querySelectorAll('p');
const target = Array.from(paragraphs).find(para => para.textContent === 'Coding everybody');
if (target !== null) {
target.textContent = 'Hello World';
}
This is my answer to the new question (getting this to work in TamperMonkey).
You could give this a try instead;
const element = document.querySelector('.username.goldbar > p');
element.innerHTML = 'Hello World';
I can't understand why I am getting this error:
Uncaught TypeError: Cannot read property 'appendChild' of undefined
Here is my code:
//create new div element, append it to the body, give it an ID and a Class.
const container_clause_1 = document.createElement("div");
document.body.appendChild(container_clause_1);
container_clause_1.setAttribute("id", "container_clause_1");
container_clause_1.classList.add("cc1");
console.log(container_clause_1);
//returns <div id="container_clause_1" class="cc1></div>"
const cClause1 = document.getElementById("container_clause_1");
console.log(cClause1);
//returns <div id="container_clause_1" class="cc1></div>"
const right_clause_1 = document.createElement("div");
console.log(right_clause_1); //returns <div></div>
document.cClause1.appendChild(right_clause_1); //Error occurs here!
I don't understand what is undefined in this situation. cClause1 is define. right_clause_1 is also defined. Granted, it's an empty div at this point, but that is what I am trying to do - add the div and then I can add the class and id, etc.
Also, I don't see any typos.
Also, if I replace document.cClause1.appendChild(right_clause_1);
with document.body.appendChild(right_clause_1); it works fine. Except that I don't want it inside the body, but rather, inside the container_clause_1 div.
I can't use JQuery for this. "Why not" is not really germane to the question. I have my reasons. Just understand that I can't use JQuery.
Well that was so obvious - after everyone started pointing out what I did wrong! Thanks for the answers!
Just another thing that this pointed out to me:
I can eliminate the variable cClause and just use container_clause_1
so my code is shorter!
const container_clause_1 = document.createElement("div");
document.body.appendChild(container_clause_1);
container_clause_1.setAttribute("id", "container_clause_1");
container_clause_1.classList.add("cc1");
const right_clause_1 = document.createElement("div");
container_clause_1.appendChild(right_clause_1);
right_clause_1.setAttribute("id", "right_clause_1");
right_clause_1.classList.add("r1");
Why have "document." in this line?
document.cClause1.appendChild(right_clause_1);
Surely you only need:
cClause1.appendChild(right_clause_1);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
In my javascript code I need to get the definition of an element, but without its content - neither text nor children.
E.g. for:
<div id="my_example_id" class="ShinyClass">
My important text
<span> Here</span>
</div>
I would like to write a javascript fucntion that when provided with the element of the div above will return the following as string:
<div id="my_example_id" class="ShinyClass">
I have been trying with different manipulations over the elements, functions like innerHTML, outerHTML and similar, but I was unable to figure out how to fetch only the part I am interested in. Is substring until the first > the best possible solution?
EDIT: selecting the element is not part of the question - I know how to do that, no prob. Rather the question is: when I have already selected a particular element how to parse as string only its own definition.
UPDATE:
const div = document.getElementById('my_example_id'); // get the node
const html = div.outerHTML.replace(div.innerHTML || '', ''); // simple set logic
console.log(html);
Just some way to do this, not saying the best.
const div = document.getElementById('my_example_id');
const copy = div.cloneNode(true);
const parent = document.createElement('div');
copy.innerHTML = '';
parent.appendChild(copy); // I forgot to add this line.
const html = parent.innerHTML;
console.log(html);
Basically you create a copy of the div, create a parent, then remove innerHTML of the copied node to leave out just the 'div' itself. Append the copied node to the new parent and show the parent's innerHTML which is just the 'div' you wanted.
you don't need to do all that fancy stuff copying it to a parent..
// make a copy of the element
var clone = document.getElementById('my_example_id').cloneNode(true);
// empty all the contents of the copy
clone.innerHTML = "";
// get the outer html of the copy
var definition = clone.outerHTML;
console.log(definition);
I threw it in a function in this fiddle: https://jsfiddle.net/vtgx3790/1/
I guess that a Regex is what you need. Check if this works for you
function getHtml(selector) {
var element = document.querySelector(selector)
var htmlText = element.outerHTML
var start = htmlText.search(/</)
var end = htmlText.search(/>/)
return htmlText.substr(start, end + 1)
}
alert(getHtml('.ShinyClass'))
example here
console.log(getElementTag("my_example_id"));
function getElementTag(myElementId) {
var FullEelementObject = document.getElementById(myElementId);
var FullElementText = FullEelementObject.outerHTML;
var regExTag = new RegExp(/(<).*(>)/i);
openingTag = FullElementText.match(regExTag);
return openingTag[0];
}
Just threw together this JSFiddle, it gets the outerHTML of the element you pass the function, the regExp to get the full opening tag.
Edit: Here is the JSFiddle
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am creating a random fact generator which will be written inside a <p> tag. I followed every tutorial there is and I don't see where is the problem. The function is being summoned normally (i check that with alert).
Here is the code:
HTML:
<p id="rfact" name="rndfact">random fact goes here</p>
JS:
function rfact(){
var nrfact=Math.floor(Math.random()*2)
alert(nrfact);
if (nrfact==0) document.getElementByName("rndfact").innerHTML="random fact1";
if (nrfact==1) document.getElementByName("rndfact").innerHTML="random fact2";
if (nrfact==2) document.getElementByName("rndfact").innerHTML="random fact3";
}
Your problem is that there is no function called getElementByName on document.
You want one of these:
document.getElementById('rfact');
document.getElementsByName('rndfact')[0] // notice the plural
You are using a method that does not exist. There is not such method as getElementByName.
Use either document.getElementsByName (note the plural in elements, you'll get an array), or document.getElementById (which is the right way to do it).
Solution: http://jsfiddle.net/P7wev/
Use getElementById, since the getElementByName you supplied in doesn't exist nor does the name attribute inside the P tag.
function rfact(){
var nrfact=Math.floor(Math.random()*2);
alert(nrfact);
if (nrfact==0) document.getElementById("rfact").innerHTML="random fact1";
if (nrfact==1) document.getElementById("rfact").innerHTML="random fact2";
if (nrfact==2) document.getElementById("rfact").innerHTML="random fact3";
}
Use document.getElementById("rfact").innerHTML=... instead.
this should work for ya.
<script type="text/javascript">
window.onload=function(){
rfact();
function rfact(){
var nrfact=Math.floor(Math.random()*2)
alert(nrfact);
if (nrfact==0) document.getElementById("rfact").innerHTML="random fact1";
if (nrfact==1) document.getElementById("rfact").innerHTML="random fact2";
if (nrfact==2) document.getElementById("rfact").innerHTML="random fact3";
}
}
</script>
HTML --> id="rndfact"
<p id="rndfact" name="rndfact">random fact goes here</p>
JS --> getElementById
function rfact() {
var nrfact = Math.floor(Math.random() * 3);
if (nrfact == 0) document.getElementById("rndfact").innerHTML = "random fact1";
if (nrfact == 1) document.getElementById("rndfact").innerHTML = "random fact2";
if (nrfact == 2) document.getElementById("rndfact").innerHTML = "random fact3";
}
rfact()
Use getElementById or use getElementsByName[0]
You have an id set use that instead. getElementsByName returns an array, you have to access the return as such, by using the array notation before accessing the properties like innerHTML
Using getElementById
function rfact(){
var nrfact=Math.floor(Math.random()*3)
alert(nrfact);
var element = document.getElementById("rfact");
if (nrfact==0) element.innerHTML="random fact1";
if (nrfact==1) element.innerHTML="random fact2";
if (nrfact==2) element.innerHTML="random fact3";
}
Using getElementsByName
function rfact(){
var nrfact=Math.floor(Math.random()*3)
var elements = document.getElementsByName("rndfact");
if (nrfact==0) elements[0].innerHTML="random fact1";
if (nrfact==1) elements[0].innerHTML="random fact2";
if (nrfact==2) elements[0].innerHTML="random fact3";
}
And use 3 instead of 2 in the formula to allow up to 3 facts.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have some HTML code that I am unable to edit without using javascript. The DIV I am trying to access is the child of another that has an ID:
<div id="contentcolumn">
<div class ="content content_gray"></div>
<div class ="forum_tabs"</div>
</div>
The DIV I am trying to access is the one with the class of "content content_gray". I do not want to access it using the class because other elements have this class. I must access it by access the first-child of the DIV with the ID of "contentcolumn".
I must access it by access the first-child of the DIV with the ID of "contentcolumn".
You mean like this?
var elm = document.getElementById("contentcolumn").firstElementChild;
You've said it's the first child, so I didn't bother to check className, but of course you can if you like. You'd add that check by doing:
if (elm.className.match(/\bcontent\b/) && elm.className.match(\bcontent_gray\b)) {
// ...
}
Note that not all browsers have firstElementChild. (I don't recall for sure whether IE8 does, for instance.) For those that don't, a simple loop does it (and works even on those that have it):
var elm = document.getElementById("contentcolumn").firstChild;
while (elm && elm.nodeType !== 1) {
elm = elm.nextSibling;
}
To you could have a little utility library you use:
function firstElementChild(parent) {
var node = parent && parent.firstElementChild;
if (!node && parent) {
node = parent.firstChild;
while (node && node.nodeType !== 1) {
node = node.nextSibling;
}
}
return node;
}
You asked below how to set the element's id once you have the element. That part's easy:
elm.id = "value";
check the element.className of each document.getElementById("contentcolumn").getElementsByTagName("div")
or else, jQuery("#id > .class") looks simpler to me