How to appendChild as third child - javascript

I want to add a new child node, after a specified node, as the third child node.
<ul id="menu">
<li>one</li>
<li>tow</li>
<li>three</li>
<li>four</li>
</ul>
<script>
var li = document.createElement("li");
document.getElementById("menu").appendChild(li);
var sometext = document.createTextNode("third one");
li.appendChild(sometext);
</script>

Use insertBefore if you want to add a node anywhere before the end of its container.
parentElement.insertBefore(newNode, currentThirdNode);

keep in mind that there is a difference in childNodes, namely siblings and ElementSiblings. a textNode is a Node, but not an Element. so if you want to insert an element into the the DOM, use nextElementSibling | previousElementSibling and appendChild | insertBefore and the parent's children attribute that only contains Elements like this:
function insertAsThird( element, parent ){
if ( parent.children.length > 2 ){
parent.insertBefore(element, parent.children[2]);
}
else parent.appendChild(element);
}
and use it like this:
insertAsThird( yourThirdElement, document.getElementById("your target parent"));
if you want to to work on childNodes, not Elements, just change the parent.children parts to parent.childNodes

I think you should append the textNode before adding the new element like this:
<script>
var li = document.createElement("LI");
var sometext = document.createTextNode("third one");
li.appendChild(sometext);
var menu = document.getElementById("menu");
var third = parent.getElementsByTagName("LI")[2];
menu.insertBefore(li, third);
</script>
I Hope this works for you..

javascript (without jQuery):
var newLi = document.createElement("li");
newLi.innerHTML ="new el 3"
var menu = document.getElementById("menu");
var el3 = menu.getElementsByTagName("li")[2];
menu.insertBefore(newLi, el3);
or with jQuery:
$('#menu').children().eq(1).append('<li>new</li>');

Related

Trouble adding element with text to DOM tree

I created an unordered list of elements and I'm trying to add a new element using DOM manipulation.
var newEl = document.create Element('li');
var newText = document.createTextNode('Hawaii');
var newEl = newEl.appendChild(newText);
document.getElementsByTagName('ul')[0].appendChild(newEl);
The element was added to the ul element but it was not added as an li element, so my new text doesn't have any bulleting.
This line
var newEl = newEl.appendChild(newText);
Change to
newEl.appendChild(newText);
When you reassign it its not the li anymore (this is not JQ)
.appendChild returns the appended element. In this case your newEl will be a text node after this assignment.
var newEl = newEl.appendChild(newText);
You should remove the assignment and it is fine.
avoid the reassignment to newEl.
var newEl = document.createElement('LI');
var newText = document.createTextNode('Hawaii');
newEl.appendChild(newText);
document.getElementsByTagName('ul')[0].appendChild(newEl);
You can try this.
Set an id to your ul element and append your new li in ul tag
var node = document.createElement("li");
var textnode = document.createTextNode("Hawaii");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
<ul id="myList">
<li>Item 1</li>
<li>Itm 2</li>
</ul>

How to appendChild an UL to a SPAN?

So, if we're going to append a LI to UL we should do this:
var list = document.createElement('li');
var ulist = document.createElement('ul');
ulist.appendChild(list);
what if I create a span, should I do this?
var list = document.createElement('li');
var ulist = document.createElement('ul);
var span = document.createElement('span');
span.appendChild(ulist);
ulist.appendChild(list);
That's the sort of thing you'd do, yes (other than the typo — missing closing '), except span elements cannot contain ul elements. The content model of span is phrasing content, but ul can only be used where flow content is expected.
You are missing a quote after ul, but your code is correct.
In your latter code, you are appending a <li> to a <ul> and this same <ul> to a <span>. You may want to append all this to the body to make them appear. See example below:
const list = document.createElement('li');
const ulist = document.createElement('ul');
const span = document.createElement('span');
span.appendChild(ulist);
ulist.appendChild(list);
document.body.appendChild(span);

How to wrap tag by another tag?

How to wrap tag by another tag? For example:
<ul>
<li>Html Tutorial</li>
<li>Mongodb Tutorial</li>
<li>Python Tutorial</li>
</ul>
I want to wrap second li element with b tag. How to do that?
you can easily do this
// element that will be wrapped
var el = document.querySelector('li:nth-child(2)');
// create wrapper container
var wrapper = document.createElement('b');
// insert wrapper before el in the DOM tree
el.parentNode.insertBefore(wrapper, el);
// move el into wrapper
wrapper.appendChild(el);
Code Snippet
// element that will be wrapped
var el = document.querySelector('li:nth-child(2)');
// create wrapper container
var wrapper = document.createElement('b');
// insert wrapper before el in the DOM tree
el.parentNode.insertBefore(wrapper, el);
// move el into wrapper
wrapper.appendChild(el);
<ul>
<li>Html Tutorial</li>
<li>Mongodb Tutorial</li>
<li>Python Tutorial</li>
</ul>
You mean this?
<li><b>Mongodb Tutorial</b></li>
Or In Javascript, assuming this is the only ul on the page. You should probably put an ID on it.
var middleOne = document.querySelectorAll( 'ul > *' )[1];
middleOne.innerHTML = "<B>" + middleOne.innerHTML + "</B>";
Wrapping li tag with another tag except ul or ol is not a good practice. You have many approach ahead but in below you can find two of them. One by css and the another one with pure js.
CSS:
ul li:nth-of-type(2) {font-weight:bold;}
/* or */
ul li:nth-child(2) {font-weight:bold;}
JS:
var ul = document.getElementsByTagName("ul")[0];
var nth = ul.getElementsByTagName("li")[1];
nth.innerHTML = "<b>"+ nth.innerHTML +"</b>";
P.S: If you really need to wrapp li element with b tag try others answers. (but it is wrong structure)

JavaScript Not able to set focus to first li element within ul

I have below code:
<ul id='someId'>
<li class='someClass'>
</li>
</ul>
I want to set focus on first li element within ul based on some condition.
My first attempt is like this:
var ul = document.getElementById('someId');
var child = ul.childNodes[0];
child.focus();
My second attempt is like this :
var y = document.getElementsByClassName('someClass');
var aNode = y[0];
aNode.focus();
But none of the above works
Any ideas?
The problem is that you can't focus a non input element without setting tabIndex.
<li tabIndex="-1">...</li>
You can Try this fiddle: jsfiddle
An 'li' can't have focus, however an 'input' can, so you write yourself the following script:
function installLI(obj){
var ul = document.createElement('ul');
obj.appendChild(ul);
var li = document.createElement('li');
var txt = document.createElement('input');
li.appendChild(txt);
ul.appendChild(li);
txt.focus();
li.removeChild(txt);
}
Where 'obj' is the object (like an editable div) that you're appending your list to.

Is there any method/way in javascript to add a child node to list element dynamically?

If I have an unordered list like
<ul id="list">
<li>Helo World-1</li>
<li>Helo World-2</li>
<li>Helo World-3</li>
</ul>
I want to add a sublist item to it dynamically. Is there any method in javascript to do that. How could I do it.
edit
I need an item at next level, i.e. a sub list of Helo World that I mentioned in OP too, something like as under. One more issue here is that I need the items to be a permanent part of my code.
<ul id="list">
<li>Helo World-1</li>
<li>Helo World-2</li>
<li>Helo World-3</li>
<ul>
<li>One</li>
<li>Two</li>
</ul>
</ul>
Using pure DOM methods:
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Your list item text"));
To add the list item to the end of the list:
ul.appendChild(li);
To insert the list item between existing list items (note you'd have to give the existing list item an id in this example):
ul.insertBefore(li, document.getElementById("list_item_id"));
Update
If you want to add a nested list, you'll need to add it to a list item rather than directly inside the list in order for it to be valid:
var lis = ul.getElementsByTagName("li");
var lastLi = lis[lis.length - 1];
var nestedUl = document.createElement("ul");
var nestedLi = nestedUl.appendChild(document.createElement("li"));
nestedLi.appendChild(document.createTextNode("One"));
lastLi.appendChild(nestedUl);
$('<li>...</li>').appendTo($('#list')); /* in jquery */
otherwise straight js
var mylist = document.getElementById('list');
mylist.appendChild(document.createElement('li'));
Note: if you need to set also text
var mylist = document.getElementById('list');
var newli = document.createElement('li');
newli.innerHTML('Helo World ' + mylist.getElementsByTagName('li').length + 1);
mylist.appendChild(newli);
I've created a sample in jsfiddle
var el = document.getElementById("list");
var li = document.createElement("li");
li.innerHTML = "item";
el.appendChild(li);
You can go through the w3schools html dom reference to see how we can manipulate the html elements using javascript.
But I think the cleaner way will be to use a third party library like jQuery which will allow a much easier way to manipulate the dom.
ex: If use jQuery this will be as easy as
$("<li>...</li>").appendTo("#list")
EDIT:
Based on your edit you can try this,
var ul = document.getElementById("list");
ul.children[2].innerHTML = "<ul><li>sub 1</li><li>sub 2</li><li>sub 3</li></ul>";
This will get the 3rd <li> of the <ul> and add a sublist to it
AFAIK, there is no equivalent HTML DOM object for list.
Anyway you can use the innerHTML:
var list = document.getElementById("list");
var item = "<li>New Item</li>";
list.innerHTML += item;

Categories

Resources