JavaScript alternative for JQuery append() in IE11 - javascript

I am trying to achieve a vanilla js alternative for jQuery append(), as I need it to work in Internet Explorer.
I need to replace $('#id2).append(link);
I have tried add innerHTML and insert into a parentNode, however I get the error 'Cannot read property 'insertBefore' of undefined'
let condition = false;
let link = '';
if (condition === true) {
link = `<li class="list>List</li>`;
$('#id1').prepend(link);
}
else {
link = `<a id="button">Button</a>`;
$('#id2').append(link);
}
Markup:
<div id="id1">
<input type="submit" id="id2">
</div>
The above code works fine in all browsers except IE11, which is a requirement. I have tried to replace $('#id2).append(link); with code below, but get error 'insertBefore' of undefined':
const div = document.querySelectorAll('#id2');
const newText = document.createElement('div');
const newText2 = newText.innerHTML = link;
div.parentNode.insertBefore(newText2, div.nextSibling);
Thank you.

You need to be working with DOM elements, not strings. Then, you can append or prepend as shown here:
// Create and configure DOM elements that will be used:
let a = document.createElement("a");
a.id = "button";
a.textContent = "Button";
let li = document.createElement("li");
li.classList.add("list");
li.textContent = "List";
// Get reference to the node to prepend/append to:
let target = document.getElementById("id1");
let answer = +prompt("1 = prepend, 2 = append");
if (answer === 1) {
target.parentNode.insertBefore(a, target);
} else {
target.appendChild(li);
}
<body>
<div id="id1">
<input type="submit" id="id2">
</div>
</body>

Related

how to exchange 2 href with respect to the presence of a text?

I need to exchange two href if a "text" is exact.
I tried lots of solutions and I thought I finally found one with a clean way but there is no change and no error. Do you have an explanation ?
let link_1 = document.getElementById('rempl_1').href;
let link_2 = document.getElementById('rempl_2').href;
$(document).ready(function() {
if (
document.getElementById('custom_field').innerHTML.indexOf('remplacement') != -1) {
let tmp = link_1;
link_1 = link_2;
link_2 = tmp;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="row">
<span class="custom_field" id="custom_field">remplacement</span>
<a class="rempl" href="my_first_url" title="original" id="rempl_1">First</a>
<a class="rempl" href="my_second_url" title="remplacement" id="rempl_2">Second</a>
</div>
You mean this?
Note I removed the need for jQuery since you were not using it anyway
window.addEventListener("load", function() {
const custom = document.getElementById('custom_field');
if (custom.innerHTML.includes('remplacement')) {
const links = document.querySelectorAll(".rempl");
const href0 = links[0].href;
const href1 = links[1].href;
links[0].href = href1;
links[1].href = href0;
}
});
<div class="row">
<span class="custom_field" id="custom_field">remplacement</span>
<a class="rempl" href="my_first_url" title="original" id="rempl_1">First</a>
<a class="rempl" href="my_second_url" title="remplacement" id="rempl_2">Second</a>
</div>
string is copied as value when assigned to new variable, so assign a new string to variable will not change href original value.
if change anchor href is what you want, you should add
document.getElementById('rempl_1').href = link_1;
document.getElementById('rempl_2').href = link_2;
for this scenario, i prefer store element as variable:
let a1 = document.getElementById('rempl_1');
let a2 = document.getElementById('rempl_2');
$(document).ready(function () {
if (
document.getElementById('custom_field').innerHTML.includes('remplacement')
) {
[a1.href, a2.href] = [a2.href, a1.href];
}
});
PS: maybe you want write replacement instead of remplacement

getting error "Cannot read property appendchild of undefined

<div class="commentArea"></div>
<input class="write" type="text">
<button onclick="summitComment()" class="summit">summit</button>
<script type="text/javascript" src="main.js"></script>
function summitComment() {
let comments = document.getElementsByClassName('commentArea')[0];
let makeDiv = document.createElement('div');
makeDiv.className = 'talking';
comments.appendChild(makeDiv)
let makeUser = document.createElement('span');
let makeMsg = document.createElement('span');
let makeBtn = document.createElement('button');
makeUser.className = "commentUserId";
makeMsg.className = "mentionUserComment";
makeBtn.className = "deleteReply";
makeMsg.innerHTML = reply.value;
makeUser.innerHTML = "User_ID";
makeBtn.innerHTML = "Delete";
for (i=0; 1; i++) {
document.getElementsByClassName('talking')[i].appendChild(makeUser)
document.getElementsByClassName('talking')[i].appendChild(makeMsg)
document.getElementsByClassName('talking')[i].appendChild(makeBtn)
}
}
I'm studying javascript and I try to make comment section for webpage.
first code is HTML code and second is JS code.
but when I write something and click summit button, it's work. but console shows to me error
Uncaught TypeError: Cannot read property 'appendChild' of undefined
I think The tag created by 'createElement' does not seem to be chosen by getElementsByClassName.
I don't know how to solve it.
The reply variable was not defined and this loop on the end I don't think it's needed
function summitComment() {
let comments = document.getElementsByClassName('commentArea')[0];
let reply = document.querySelector('.write');
let makeDiv = document.createElement('div');
makeDiv.className = 'talking';
comments.appendChild(makeDiv);
let makeUser = document.createElement('span');
let makeMsg = document.createElement('span');
let makeBtn = document.createElement('button');
makeUser.className = "commentUserId";
makeMsg.className = "mentionUserComment";
makeBtn.className = "deleteReply";
makeMsg.innerHTML = reply.value;
makeUser.innerHTML = "User_ID";
makeBtn.innerHTML = "Delete";
makeDiv.appendChild(makeUser)
makeDiv.appendChild(makeMsg)
makeDiv.appendChild(makeBtn)
}
<div class="commentArea"></div>
<input class="write" type="text">
<button onclick="summitComment()" class="summit">summit</button>
<script type="text/javascript" src="main.js"></script>
Because appendChild cannot read from undefined
You need check Element exist before append instead of:
var element = document.getElementsByClassName('talking');
for (i=0; 1; i++) {
element?.[i]?.appendChild(makeUser)
element?.[i]?.appendChild(makeMsg)
element?.[i]?.appendChild(makeBtn)
}
Try to use
if (!!comment) comments.appendChild(makeDiv)
instead of only
comments.appendChild(makeDiv)
getElementByClassName returns a single DOM element. You don't need to do '[0]' on it. Remove that and it should work fine.
In case if you use querySelectorAll, then you have get by index since this method returns an array.

adding and delete script doesn't work with removeChild()

I'm having some trouble with my code. the only thing i have to make is an add and delete button. The adding part is already done, but the delete part not. it keeps saying:
uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'
Can someone please help me?
Thanks!
Code:
<input type="text" id="txtelement">
<button id="add">result</button>
<button id="delete">Delete latest</button>
<p id="divResult"></p>
<script>
//decline variable
var index = 1;
//adding option
window.onload = function(){
document.getElementById('add').onclick = function(){
var newElement = document.createElement('div');
varElementid = 'div' + index++;
var node = document.getElementById('txtelement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
}
//delete option
document.getElementById('delete').onclick = function(){
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('p:last-child')[0];
console.log(alinea + ' word verwijderd...');
divResult.removeChild(alinea);
console.log('verwijderd!');
}
}
:last-child works slightly different than you think it does. p:last-child selects the last child of type p(aragraph) of [whatever parent node you called the method on]'. You don't want to select the p, you want to select the div you just inserted.
var alinea = divResult.querySelectorAll('div:last-child')[0]
Do note that your code doesn't handle the case yet where you delete more elements than you added.
Running code snippet:
//decline variable
var index = 1;
//adding option
window.onload = function() {
document.getElementById('add').onclick = function() {
var newElement = document.createElement('div');
varElementid = 'div' + index++;
var node = document.getElementById('txtelement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
}
//delete option
document.getElementById('delete').onclick = function() {
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('div:last-child')[0];
console.log(alinea + ' word verwijderd...');
divResult.removeChild(alinea);
console.log('verwijderd!');
}
}
<input type="text" id="txtelement">
<button id="add">result</button>
<button id="delete">Delete latest</button>
<p id="divResult"></p>

How to remove objects within a todo?

Here is my code for my current todo list.
<html>
<head>
<title>ToDo</title>
</head>
<body>
<script>
function addText(){
var input = document.getElementById('input').value;
var node = document.createElement("P");
var textnode = document.createTextNode(input);
node.appendChild(textnode);
document.getElementById('do').appendChild(node);
}
</script>
<p id="do"> </p>
<input type='text' id='input'/>
<input type='button' onclick='addText()' value='Add To List'/>
</body>
</html>
It works to add objects but I have no idea what the javascript is to remove objects?
I wonder if someone could help me with a remove script like a X mark on the side of a new added object or something just to remove 1 after you add it,
Cheers
I think I found a solution to your problem. Check my fiddle:
http://jsfiddle.net/Kq4NF/
var c = 1;
function addText(){
var input = document.getElementById('input').value;
var node = document.createElement("P");
node.setAttribute('id', 'anchor'+c);
var textnode = document.createTextNode(input);
node.appendChild(textnode);
var removenode = document.createElement("input");
removenode.setAttribute('type', 'button');
removenode.setAttribute('value', 'X');
removenode.setAttribute("onclick", "removeText('anchor"+c+"')");
node.appendChild(removenode);
c++;
document.getElementById('do').appendChild(node);
}
function removeText(item){
var child=document.getElementById(item);
document.getElementById('do').removeChild(child);
}
Good luck!
var list = document.getElementById("do");
list.removeChild(list.childNodes[0]);
list - represents the p tag with ID do
list.ChildNodes - list of child elements appended to your p tag with ID as do.
list.ChildNodes[0] - represents the first child appended to the list, where 0 is the index.
To remove a specific element, either represent the is as index or point directly the element like
var list = document.getElementById("do");
var node = document.createElement("P");
var textnode = document.createTextNode(input);
textnode.id = "do1"; // Add id to the child element
node.appendChild(textnode);
document.getElementById('do').appendChild(node);
// This is to remove it using ID
list.removeChild(document.getElementById("do1"));
Hope you can understand.

Remove existing code side of div code

Goal:
If there are any html syntax code or data inside of
<div id="feedEntries"></div>
Then everything should be removed and be contained empty only.
Problem:
What syntax do I need in order to remove every code and data inside of
<div id="feedEntries"></div>
Please remember that i don't want to add any class or id inside of "feedEntries"
<h3>Search</h3>
<div class="content">
<form>
<input type="text" width="15" value="searchword" id="searchTermTextField"><input type="button" name="some_name" value="Sök" id="searchButton">
</form>
<div id="feedEntries">
</div>
</div>
function fetchSearchResults(json) {
var feedEntriesDivElement = document.getElementById('feedEntries');
var ulElement = document.createElement('ul');
if (feedEntriesDivElement.children.length >= 0)
{
// Syntax code to remove the code/data
}
for (var i = 0; i < json.responseData.results.length; i++)
{
var liElement = document.createElement('li');
var personText = document.createTextNode(json.responseData.results[i].titleNoFormatting);
var newlink = document.createElement('a');
newlink.setAttribute('href', json.responseData.results[i].url );
newlink.appendChild(personText);
liElement.appendChild(newlink);
ulElement.appendChild(liElement);
}
feedEntriesDivElement.appendChild(ulElement);
}
Using pure DOM and Javascript (sometimes considered better than altering innerHTML):
if ( feedEntriesDivElement.hasChildNodes() )
{
while ( feedEntriesDivElement.childNodes.length >= 1 )
{
feedEntriesDivElement.removeChild( feedEntriesDivElement.firstChild );
}
}
feedEntriesDivElement.innerHTML = ''; should do the trick.
you can use jquery like this $('#feedEntries').empty()
to remove from javascript please check the post
document.getElementByIf('feedEntries').innerHTML = ''

Categories