Unable to Append Child in JavaScript using appendChild - javascript

I am trying to append some html which is coming as a string in a div but some how appendChild is not working as expected here is my JS code:
var doc = document.getElementById("products");
var notes = doc.getElementsByClassName("product_grid");
var str = '<div>New Node 3<div><div>New Node 4<div>';
var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
notes.appendChild(child);
Here is my HTML:
<div id="products" >
<div class="product_grid">
<div>
Existing node 1
<div>
<div>
Existing node 2
<div>
</div>
</div>
What is wrong with it its unable to Identify the appendChild as a function and keeps giving me error TypeError: notes.appendChild is not a function here is working fiddle

notes is a NodeList. So you'll have to use index to select the elements.
Try this:
notes[0].appendChild(child); // Appends to first product_grid

Related

I dont understand the why this UNDEFINED happen in JavaScript

Why this code return me undefined in the DOM when i don't put the [0]
var d = document.getElementsByName('msg')[0]
document.write(`<br> ${d.innerText}`)
<div id="msg" name="msg">click here</div>
just trying to understand JS in depth
var d = document.getElementsByName('msg')
document.write(`<br> ${d.innerText}`)
<div id="msg" name="msg">click here</div>
Because get elements will return a collection of elements not a single element
try get element by id

Getting the actual name of the class, and not the element within it?

To get elements using a class name, document.getElementsByClassName() can be used.
But is there a function in JavaScript to get the actual name of the class itself?
Example:
var classElement = document.getElementsByClassName('myClass');
var printResult = document.getElementById('result');
printResult.innerHTML = classElement[0].innerHTML;
<div class="myClass">Hello</div>
<div id="result"></div>
printResult will just print out "Hello". What if I want the result to print out the string "myClass" which is the actual class name?
I tried classElement[0].className.innerHTML but it returns undefined.
className is a property of the dom node containing the classes of the element.
You don't need to add innerHTML, which is another property of the dom node and returns/sets the html content of the corresponding element.
var classElement = document.getElementsByClassName('myClass');
var printResult = document.getElementById('result');
printResult.innerHTML = classElement[0].className;
<div class="myClass">Hello</div>
<div id="result"></div>

How to append an element before another using Javascript?

I tried following the a wiki and looking into multiple questions here but I still have problems with insertBefore..
This is my sample:
<div id="container">
<span id="first">1</span>
<span id="second">2</span>
<div id="third">3</div>
<div id="forth">4</div>
</div>
<script>
topbar = document.getElementsById("container");
boardlist = document.getElementsById("first");
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML("0");
topbar.inserBefore(bmcontainer, boardlist);
</script>
I want to append the span#zero before the span#first. What am I doing wrong? I'm trying to not use jQuery, so I'm looking for a totally javascript solution.
Node.insertBefore() is the answer.
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
If you have Parent Node, then you should use ParentNode.prepend()
ParentNode.prepend(nodesToPrepend);
Take a look # mentioned links for full documentation and examples.
Update
You have some issues in your code (typo and wrong usage of innerHTML), here is fixed code.
HTML
<div id="container">
<span id="first">1</span>
<span id="second">2</span>
<div id="third">3</div>
<div id="forth">4</div>
</div>
JS
var topbar = document.getElementById("container"),
boardlist = document.getElementById("first"),
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML = "0"; // innerHTML is not a function, it's a property
topbar.insertBefore(bmcontainer, boardlist);
jsfiddle
Notice that InnerHTML is not a function, it's a property, read more about that here: Element.innerHTML
Prepend pure javascript
MDN article on insertBefore()
var el = document.getElementById('thingy'),
elChild = document.createElement('div');
elChild.innerHTML = 'Content';
// Prepend it
el.insertBefore(elChild, el.firstChild);
Source: http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/#Prepend
Also, the jQuery prepend() Method
You can read about it here and here.
You can use the insertAdjacentElement function.
var boardlist = document.getElementById("first"),
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
boardlist.insertAdjacentElement('beforebegin', bmcontainer);
Element.insertAdjacentElement

get html from a variable by id

i have a variable name value in my javascript code that contain html data.i want to get the data inside form specific id that is inside #myDiv
var value="<div >
<p class="">Hi cname#gmail.com</p>
<br/>
<br/>
<br/>
<div id="myDiv">
sgdhsagdhagh
dhsajdgasj
cjzjcg
</div>
</div>"
Thanks
You should create a DOM element, then traverse up to it and get html() or .text()
var value = '<div >\
<p class="">Hi cname#gmail.com</p>\
<br/>\
<br/>\
<div id="myDiv">\
sgdhsagdhagh\
dhsajdgasj\
cjzjcg\
</div>\
</div>';
alert($(value).find('#myDiv').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you need to get parent element, then use
alert($('<div />', {html: value}).find('#myDiv').html())
How about you do like this?
var variable = "stuff n things";
document.getElementById( 'myDiv' ).innerHTML = variable;
Thats the native way :)
EDIT:
if you want to get the data you just do like this:
var variable = document.getElementById( 'myDiv' ).innerHTML;
That will give you the markup of whats inside the div.
Or use document.querySelector("#myDiv") to get the first match on the selector.querySelectorAll returns array.
You can use the HTML of the value variable to create an jQuery object. From this object you can search for the element with the id, and get its HTML content:
var html = $(value).find('#myDiv').html();
console.log(html); //sgdhsagdhaghdhsajdgasjcjzjcg
Or a pure javascript implementation:
var el = document.createElement('div');
el.innerHTML = value;
var html = el.getElementById('myDiv').innerHTML;
console.log(html); //sgdhsagdhaghdhsajdgasjcjzjcg
Using plain Javascriptuse:
document.getElementById("myDiv").innerHTML;
Using jQuery:
$("#myDiv").html();
There are Two ways- Angular way-
var elem = angular.element(value);
var innerDive=elem[0].getElementById('myDiv');
var text= angular.element(innerDive[0]).innerText;
Jquery-
var text= $(value).find('#myDiv').text();

how to remove the lastchild element of dynamically generated DIV and return the html as string

How to remove the lastchild of the dynamically generated div and regenerate the html as string.
Sample HTML DIV
strHtmlString = "<div contenteditable='true' id='undefined'>Test1</div>
<div contenteditable='true' id='sentenceFreeTextField67' type='sentenceFreeTextField'>One</div>
<div id='multiselectAnchors' type='multi'>
<div id='options32' >Two</div>
<div contenteditable='true' id='sentenceFreeTextField68' type='sentenceFreeTextField'>One</div>
</div>
<div id='blank4' contenteditable='true' type='blankField'> </div>
<div id='Div1' type='multi'>
<div id='options33' >Three</div>
<div contenteditable='true' id='sentenceFreeTextField69' type='sentenceFreeTextField'>One</div>
</div>"
here is the code sample
if (($('<DIV/>').html(strSentence)[0].lastChild.lastChild.type === 'sentenceFreeTextField') && (!$.trim($('<DIV/>').html(strSentence)[0].lastChild.lastChild.innerText))) {
strHtmlString = $('<DIV/>').html(strSentence)[0].lastChild.lastChild.remove().html; (this remove().html doesn't work)
}
the need is to delete the lastchild of the div at runtime and convert back to string as it was earlier. I can do string manipulation however, might not the be the right way, please suggest
var el = $(strHtmlString);
// dont know what you meant by last child, so taking the id
el.children().find("#sentenceFreeTextField69").remove();
var str = el.wrap("<div/>").parent().html()
Generate a DIV dynamically:
$('body').append('<div>');
Access the DIV immediately after generation:
var $divElement = $('body').append('<div>').find('div');
Get the last child:
var $lastChildElement = $divElement.last();
Get the HTML of the last child (more specifically, the innerHTML):
var $lastChildHTML = $lastChildElement.html();
Do it all together then you turn around:
var $lastChildHTML = $('body').append('<div>').find('div').last().html();
That's what it's all about.
var last = $(element).children(':last-child');
var html = $(last).html();
$(last).remove();
var newHtml = $(element).html();
//incase you want the html with it's parent as well do this
var newHtml = $(element).parent().html();

Categories

Resources