Appending child node by javascript - javascript

I have dynamically generated html thru ajax when a page is loading, something like this,
Dynamically inserted,
<p class="Hello">
<span id='click lvl1'>1</span>
<span>2</span>
</p>
Now, I am trying to add another node into my <p> element. Again, dynamically thru ajax.
Server response is something like,
<p class="Hello lvl2">
<span id='click'>1</span>
<span>2</span>
</p>
Which I want to insert into the element which I have got first time.
final result,
<p class="Hello">
<span id='click'>1</span>
<span>2</span>
<p class="Hello lvl2">
<span id='click'>1</span>
<span>2</span>
</p>
</p>
While making an second ajax call I am getting reference to <span id='click lvl1'>1</span> element.
What have I tried so far?
Everthing, I could try I have tried but I am not able to inset the node. I am assuming that I am doing something really wrong. My attempts are,
pElement is <span id='click'>1</span>
pElement.parent().appendChild(data.expandTreeVal);
pElement.parent().append(data.expandTreeVal);
pElement.parent().after(data.expandTreeVal);
pElement.parentNode().appendChild(data.expandTreeVal);
Debugging
Do I really get anything from server?
Yes, When I do alert(data.expandTreeVal); it shows me my desired HTML.
any thoughts will be a great help.

You can only append DOM elements to an element, you can't append HTML code in a string.
Create an element, use the innerHTML method to put the HTML code in it, then get the first child node from it to get the p element as a DOM element.
var div = document.createElement('DIV');
div.innerHTML = data.expandTreeVal;
var p = div.childNodes[0];
Then you can add it to the document using the parentNode and appendChild methods:
pElement.parentNode.appendChild(p);
Demo: http://jsfiddle.net/AfVfE/

You may need to post a full blown use case for me to fully understand, but I think that the whole issue is that you're referencing methods that don't exist.
My use case worked fine like this:
<p class="Hello">
<span id='click'>1</span>
<span>2</span>
<p class="Hello lvl2">
<span id='click'>1</span>
<span>2</span>
</p>
</p>
With this JS:
​var pElement = document.getElementById('click');
alert(pElement.parentNode);​​​
​

Related

getElementById not working in class method

HTML:
<div id='verse'>
<p id='text'>
<span id = 'reference'>random stuff here</span>
random stuff here
</p>
</div>
JS:
class Verse {
...
update() {
document.getElementById('text').innerHTML = 'text';
document.getElementById('reference').innerHTML = 'reference';
}
...
}
Whenever I call .update in an instance of Verse, the paragraph element's text changes without a problem but trying to change the span's text gives me an error: TypeError: Cannot set properties of null. Does not work with innerText either. It works fine if I change it outside of the class. Thanks for the help!
Setting innerHTML on #text replaces the contents of the <p> entirely, so when you subsequently try to access #reference it no longer exists.
The simplest way to avoid this would be to add another span and replace its text instead of the entire <p>.
<div id='verse'>
<p>
<span id='reference'>random stuff here</span>
<span id='text'>random stuff here</span>
</p>
</div>

JavaScript: How to replace code within element without innerHTML

I want to replace content within element in JavaScript but I cannot use innerHTML and jQuery.
For example:
<div id="MyID">
<b>Hi,</b> how are you?<br/>
I am fine.
</div>
I want to replace everything between <div id="MyID"> and </div>.
Like via innerHTML which I sadly cannot use:
document.getElementById('MyID').innerHTML = document.getElementById('MyID').innerHTML.replace(/you/, 'you');
Which will be:
<div id="MyID">
<b>Hi,</b> how are you?<br/>
I am fine.
</div>
How to do it?
I tried things like appendChild and removeChild but I still cannot figure it out.
For appendChild, you should append a dom entity
Use remove() to clear the existing content and then insertAdjacentHTML() to enter the new content. Here is your code sample as an example.
<div id="MyID">
<span id="MyID2">
<b>Hi,</b> how are you?<br/>
I am fine.
</span>
</div>
<button onclick="myFunction()">Insert a paragraph</button>
<script>
function myFunction() {
var a = document.getElementById("MyID2");
a.remove();
var b = document.getElementById("MyID");
b.insertAdjacentHTML('afterbegin', '<b>Hi,</b> how are you?<br/>I am fine.');
}
</script>

Jquery: get content of node excluding span

Have HTML of the following form:
<h1 class="someClass"> Want this <span class="anotherClass"> don't want this </span> </h1>
How do I use js or jquery (preferred) to grab the "Want this" text, excluding the span text?
You may do that in plain JS. Just extract the contents of the first child node of the h1.
console.log(
document.querySelector('h1').childNodes[0].nodeValue.trim()
);
<h1 class="someClass">
Want this
<span class="anotherClass">don't want this</span>
</h1>
This did it:
$('.someClass').contents().get(0).nodeValue.trim();

JavaScript fetching values from div tag

Hi I'm new to JavaScript. I need to fetch value 'KARTHIK' from the following code using document.getElement,
<div class="account-info">
<h3 class="account-header">Welcome back,</h3>
<p>
<strong>KARTHIK</strong><br>
</p>
</div>
Any one help me in this. Thanks in advance.
You can use innerHTML
you just have to give the strong tag an id.
<strong id="ih">KARTHIK</strong>
<script>var innerStrong=document.getElementById("ih").innerHTML;</script>
You can get the element by its tag:
alert(document.getElementsByTagName("strong")[0].innerHTML);
<div class="account-info">
<h3 class="account-header">Welcome back,</h3>
<p>
<strong>KARTHIK</strong><br>
</p>
</div>
However, get elements by the tag name can be unreliable, because there may be more than one <strong> tag. Thus, it would be advisable to assign an id to the element:
alert(document.getElementById("account-name").innerHTML);
<div class="account-info">
<h3 class="account-header">Welcome back,</h3>
<p>
<strong id="account-name">KARTHIK</strong><br>
</p>
</div>
You can use querySelector of document object to get this easily.
document.querySelector("div.account-info strong").innerHTML
Refer this jsbin

body.innerHTML before/after nth-child

Is it possible to add something with innerHTML before/after the nth child of <body>?
e.g.:
<html>
<head></head>
<body>
<div id="first">First</div>
<div id="second">Second<div id="second_sub"></div></div>
<div id="third">Third</div>
</body>
</html>
I can add at the beginning with body.innerHTML = html + body.innerHTML and at the end with body.innerHTML += html but how to add, for example, before the second <div>?
I don't want to use replace on <div id="second"> as the source changes and the insert should be done at random. Is there a solution with innerHTML or do I need to switch to Dom Nodes? Would be slow in old browsers :(
You are probably looking for the insertBefore method. It will insert a child before the given element. Alternatively there's the appendChild method which will always push elements on the beginning of the given element.
Examples:
<body>
<span id="elem1">Hello</span>
<span id="elem2">World</span>
</body>
Let's assume we're inserting a new element stored in the var newElem:
document.insertBefore(newElem, document.getElementById("elem2")) will give:
<body>
<span id="elem1">Hello</span>
<!-- New element here! -->
<span id="elem2">World</span>
</body>
document.appendChild(newElem) will give:
<body>
<!-- New element here! -->
<span id="elem1">Hello</span>
<span id="elem2">World</span>
</body>
I'm using this by now (Thanks to ajax333221):
e = document.createElement('div');
e.innerHTML = '<div>... huge content with several sub elements ...</div>';
document.body.insertBefore(e, document.body.childNodes[2]);
This is a combination of both techniques. With this I'm able to use the fast .innerHTML without extremely blowing up the code with createElement(), setAttribute(), etc.
Other solutions are welcome.

Categories

Resources