Adding an ID to the child of an element [closed] - javascript

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

Related

How do I change edit/change <p> text html type? [closed]

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';

Javascript element html without children [closed]

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

can not parse getElementById [closed]

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 7 years ago.
Improve this question
I have this function which produces the correct value when run, but I am having a hell of a time displaying the results.
Here is the JS which is calculated onChange in a form I am trying to display the resulting value elsewhere on the form. The alert displays the correct value but my id remains blank.
Thanks in advance for taking a look
function calculate_mtow1() {
togw_n = 0;
togw = $('#togw').val();
if (togw != '' && togw != 0 && togw != 'Nan') {
var togw = togw.replace(",", "");
togw_n = togw;
}
burn_n = 0;
burn = $('#burn').val();
if (burn != '' && burn !=0 && burn != 'Nan') {
var burn = burn.replace(",", "");
burn_n = burn;
}
var mtow1 = parseInt(togw_n) + parseInt(burn_n);
$('#mtow1').val(mtow1);
document.getElementById('mtow1');
alert(mtow1);
}
<td>TOW + Fuel Burn =<span id="mtow1"></span></td>
Your code is getting the element with getElementById but then not doing anything with it. You need to assign the result of getElementById to something, or call methods on it on the same line. If your goal is to put the value of mtow1 into your <span>, try doing this:
// Solution 1
var spanElement = document.getElementById("mtow1");
spanElement.innerHtml = mtow1;
Alternatively, perhaps you were trying to display the value of mtow1 by using this jQuery:
$('#mtow1').val(mtow1);
That doesn't do what you think it does. It changes the "value" attribute of the span to the value of mtow1, but that change isn't visible to the user. It's the same as writing this as your HTML:
<td>TOW + Fuel Burn =<span id="mtow1" value="valueofmtow1"></span></td>
If you want to use jQuery instead of the getElementById method I posted above, you could do this:
// Solution 2
$('#mtow1').html(mtow1);
You don't need to do both. Either solution will work on its own.

Create a div a child of another div in javascript (DOM) [closed]

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/

IF ElementID value then change another ElementID value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
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.
Improve this question
I'm trying to lookup a field's value, if it equals '1', then put the value '1' in different field, if not put a '0'.
I'm not sure why this isn't working, can anyone help?
<input type="text" name="_1_1_33_1_id" value="" onchange="checkLineManager();">
<input class="valueeditable" type="text" name="_1_1_118_1" id="_1_1_118_1" value="" >
Javascript:
function checkLineManager() {
if (document.getElementsByName('_1_1_33_1_id').value == '1') {
document.getElementById('_1_1_118_1').value = '1';
} else {
document.getElementById('_1_1_118_1').value = '0';
}
}
http://jsfiddle.net/nbren007/o9xp0efy/
Note the plural use of "elements" in the following line:
if (document.getElementsByName('_1_1_33_1_id').value == '1') {
This doesn't return an element, it returns a node list.
// To confirm that
alert(document.getElementsByName('_1_1_33_1_id').toString());
So you need to use:
if (document.getElementsByName('_1_1_33_1_id')[0].value == '1') {
There are other ways of accessing the element as well. Most notably through the form element approach.
The hint is in the method: getElementsByName returns more than one element - it returns an array of matching elements.
You need to use array notation to select the element from the array.
Change:
document.getElementsByName('_1_1_33_1_id')
To:
document.getElementsByName('_1_1_33_1_id')[0]
if (document.getElementsByName('_1_1_33_1_id')[0].value == '1') {
document.getElementById('_1_1_118_1').value = '1';
} else {
document.getElementById('_1_1_118_1').value = '0';
}
Or even neater, use a ternary statement:
document.getElementById('_1_1_118_1').value =
document.getElementsByName('_1_1_33_1_id')[0].value == 1 ? '1' : '0';

Categories