Remove HTML Element in a parent HTML Element - javascript

I have a basic table and one column should have an active/waiting badge.
I receive this information by my implemented Websocket. Works fine so far.
I was able to add at initial rendering the badge to the column that it looks like this:
<td th:id="${car.getBrand()}"><span value="${car.getBrand()}" class="badge badge-success">Active</span></td>
or this
<td th:id="${car.getBrand()}"><span value="${car.getBrand()}" class="badge badge-light">Waiting</span></td>
This was implemented by the help of this code and does what it should do:
var tableEntry = document.getElementById(message.content[0])
if (message.content[1] === 'true') {
var span = document.createElement('span')
span.value = message.content[0]
span.innerHTML = '<span class="badge badge-success">Active</span>'
tableEntry.appendChild(span)
} else {
var span = document.createElement('span')
span.value = message.content[0]
span.innerHTML = '<span class="badge badge-light">Waiting</span>*'
tableEntry.appendChild(span)
}
What is my problem?
The last hours I spent with trying to remove the existing span element inside the <td>...</td> before I insert the new span code with the function I created above. The matching entry should be found by the span attribute value. I really tried hard but I am giving up now.
Please help me.

Depending on what exactly you want to do, you need to either edit the exact node you want directly, or remove the old node and append a new node. Without more context, I'll suggest replacing the node outright:
var tableEntry = document.getElementById(message.content[0])
// Note that we can move the duplicated code to outside if block
// and make it clearer as to exactly the difference between the
// branches
var span = document.createElement('span')
span.value = message.content[0];
if (message.content[1] === 'true') {
span.innerText = 'Active';
span.className = 'badge badge-success';
} else {
span.innerText = 'Waiting';
span.className = 'badge badge-light';
}
// Here we remove all children
while (tableEntry.firstChild)
tableEntry.removeChild(tableEntry.firstChild);
// ... before add the new content
tableEntry.appendChild(span);
Edit
If you would rather do this with jQuery, try:
var $newSpan = $('<span>', {'class': 'badge'});
var $td = $('#' + message.content[0]);
if (message.content[1] === 'true')
$newSpan.addClass('badge-success').text('Active');
else
$newSpan.addClass('badge-light').text('Waiting');
$td.empty().append( $newSpan );
Alternatively, you could update the span that's there directly:
if ( message.content[1] === 'true' )
$('#' + message.content[0]).find('span').removeClass('badge-light').addClass('badge-success').text('Active');
else
$('#' + message.content[0]).find('span').removeClass('badge-success').addClass('badge-light').text('Waiting');

Are you just looking for this:
$('td').find('span').remove();
Maybe i am missing something here though, and if so i can better write up a answer. Since i am not sure what is within "message.content[n]", why dont you when building the span, also add a unique ID to it. That way when you go to update the span in your javascript, you can reference the correct one to remove, then append?
//remove it
$('td').find('#yourSpanId').remove()
//now assign id to new span object
span.id = message.propetyToUseAsId //i do not know all properties of your object
var span = document.createElement('span')
span.value = message.content[0]
span.innerHTML = '<span class="badge badge-light">Waiting</span>*'
/*********** soemthing like this *************/
span.id = message.propetyToUseAsId //i do not know all properties of your object
tableEntry.appendChild(span)
Does this help? Would be easier if we could see all object properties, and look for object ID or something unique to each object you could use as the id. I like to use custom attributes instead of ID's when building template like this, so i can reference anything based on each object later in page cycle or life quickly.

Since I was asked by an admin to post the solution here, I do it.
This is the code that does the job
var message = JSON.parse(payload.body)
var tableEntry = document.getElementById(message.content[0])
tableEntry.removeChild(tableEntry.firstChild)
if (message.content[1] === 'true') {
tableEntry.innerHTML = '<span class="badge badge-success">Active</span>'
} else {
tableEntry.innerHTML = '<span class="badge badge-light">Waiting</span>'
}
Thank you for your help, I wouldn't make it without you :)

Related

How do we convert jQuery prepend() to VanillaJS [duplicate]

How can I implement prepend and append with regular JavaScript without using jQuery?
Here's a snippet to get you going:
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.
Perhaps you're asking about the DOM methods appendChild and insertBefore.
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the
existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of
children. Equivalently, and more readably, use
parentNode.appendChild(newChild).
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element?
If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML, with appropriate first argument:
'beforebegin'
Before the element itself.
'afterbegin'
Just inside the element, before its first child.
'beforeend'
Just inside the element, after its last child.
'afterend'
After the element itself.
Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO
Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.
I added this on my project and it seems to work:
HTMLElement.prototype.prependHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
this.insertBefore(div, this.firstChild);
};
HTMLElement.prototype.appendHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
while (div.children.length > 0) {
this.appendChild(div.children[0]);
}
};
Example:
document.body.prependHtml(`Hello World`);
document.body.appendHtml(`Hello World`);
Here's an example of using prepend to add a paragraph to the document.
var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);
result:
<p>Example text</p>
In order to simplify your life you can extend the HTMLElement object. It might not work for older browsers, but definitely makes your life easier:
HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;
HTMLElement.prototype.prepend = function(element) {
if (this.firstChild) {
return this.insertBefore(element, this.firstChild);
} else {
return this.appendChild(element);
}
};
So next time you can do this:
document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:
HTMLDivElement.prototype.prepend = (node, ele)=>{
try { node.insertBefore(ele ,node.children[0]);}
catch (e){ throw new Error(e.toString()) } }
Simple arrow function that's compatible with most modern browsers.
var insertedElement = parentElement.insertBefore(newElement, referenceElement);
If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.
insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.
Examples can be found here: Node.insertBefore
You can also use unshift() to prepend to a list
document.write() is not a good practice, some browsers like Chrome give you a warning if you use it, and it may be a bad solution if you are providing it to a customer, they don't want to use your code and see warnings in the debug console!
Also jQuery may also be a bad thing if you are giving your code to a customer who already uses jQuery for other functionality on their site, there will be a conflict if there is already a different version of jQuery running.
If you want to insert content into an iframe, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

How to insert multi values to data-tag

I made a jquery filter function, that filtering the results by data-tags. like this:
<div class="resultblock" data-tag="ios">
<img src="images/osx.jpg" class="itemimg">
<div class="desc">
<div class="desc_text">
lorem ipsum
</div>
</div>
i just want to insert in the data-tag another tags to filter. like this:
data-tag="ios,android,windows"
How can i do that?
I am not sure I fully understand the question you are asking, but I think you could accomplish this via JS.
In your html add a script tag and then you just write some JS to edit or add html tags. Here is an example:
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
Now to sort the data-tag:
just add this code to your HTML file.
<div id="div1">
</div>
<script>
var tag ="ios,android,windows"; //initialize variable
var data = tag.split(","); //this makes an array of ios,andrid,windows
var i = 0;
while (i < 3){
alert(i);
var para = document.createElement("p");
var node = document.createTextNode(data[i]);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
i++;
}
</script>
The best way doing this is to use classes. Adding classes and removing them is much easier than other attributes. The classes should not overlap with other classes used for CSS for example. Adding a prefix to them is even better. Like this:
$(".filter-ios").hide(); // hide all ios elements
$("something").addClass("filter-windows"); // add the class windows to an element
$(".filter-ios").addClass("filter-apple"): // add the apple filter class to the ios filter class elements
$("something").hasClass("filter-samsung"); // check if an element has the filter class samsung
// ...
The classes .filter-* should be used for filtering only, they must not have any CSS attached to them, if there is already classes like that, then just change the prefix filter to something else!
I've just created a little object with two methods .add and .remove. It works like classList DOM method for adding and removing classes. If you add one value twice, it's added only once, also if you remove some not existing class, any error will occure. Hope you'll find it helpful.
var el = document.getElementById('myElem');
multiValues = {
add: function(elem,val){
if(elem.constructor.toString().search('HTML')===-1) return;
if(typeof val !=='string') return;
if(!elem.attributes['data-tag']) elem.setAttribute('data-tag');
var attr = elem.attributes['data-tag'];
var parsed = attr.value.split(',');
var isExist = parsed.some(function(a){
return a === val;
});
if(!isExist) parsed.push(val);
elem.setAttribute('data-tag',parsed.join(','));
},
remove: function(elem,val){
if(elem.constructor.toString().search('HTML')===-1) return;
if(typeof val !=='string') return;
if(!elem.attributes['data-tag']) return;
var attr = elem.attributes['data-tag'];
var parsed = attr.value.split(',');
parsed.some(function(a,b){
if(a===val){
parsed.splice(b,1);
}
elem.setAttribute('data-tag',parsed.join(','));
});
}
};
multiValues.add(el,'window');
multiValues.add(el,'window');
multiValues.add(el,'window');
multiValues.add(el,'android');
multiValues.remove(el,'a');
multiValues.remove(el,'b');
multiValues.add(el,'something');
console.log(el.attributes['data-tag'].value);
<div class="resultblock" data-tag="ios" id="myElem"></div>

Using createTextNode() but I need to add HTML tags to it (JavaScript/JQuery)

When I click an item in a table, I need it to add that item to a list and display that list.
Here's my code for adding/displaying the items in the list:
var myList = document.getElementById('my-list');
function addItemToList(id) {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(id));
myList.appendChild(entry);
};
This works great, but I also need to add a "delete" button to each item in the list.
But when I add + ' delete' to the createTextNode() parameter, it doesn't work. This is because, obviously, textNodes can only have plain text.
So how do I make this code work with the HTML tag? Is there any JS or Jquery method other than createTextNode() that will do the same thing, but allow HTML tags?
With the specific scenario you mention, you would just set innerHTML of the li
entry.innerHTML = id + ' delete'
Otherwise, either create the element like you did for the li, but using an a instead, and append it. Or just use insertAdjacentHTML() to append the whole thing
Creating the element
var entry = document.creatElement('li');
entry.appendChild(document.createTextNode(id));
var link = document.createElement('a');
link.href = "#";
link.innerText = "delete";
entry.appendChild(link);
Using insertAdjacentHTML
entry.insertAdjacentHTML('beforeend',id + ' delete');
Demo
var id = "Some Text";
var list = document.querySelector("ul");
var entry = document.createElement("li");
entry.insertAdjacentHTML("beforeend", `${id} delete`);
list.appendChild(entry);
<ul></ul>
Also since you tagged jQuery, you can do the same thing as insertAdjacentHTML but by calling jQuery's append() method
$(entry).append( id + ' delete' );
One possibility would be:
function addItemToList(id) {
var entry = document.createElement('li');
entry.innerHTML = id + 'delete';
myList.appendChild(entry);
};
I'm not sure if there are any particular reasons you're using createTextNode() or avoiding jQuery selectors, but if it's simply because you're new to jQuery overall, than this code snippet has some updates with better practices and solves your problem. Hope it helps!
var $myList = $('#my-list');
function addItemToList(id) {
var $deleteLink = $('Delete');
$deleteLink.on('click', function(e) {
e.preventDefault();
$(this).parent().remove()
})
var $entry = $('<li>'+id+'</li>')
$entry.append($deleteLink)
$myList.append($entry);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="my-list">
</ul>
Add Item

appendChild() and createElement() Javascript question

When I use appendChild() and createElement() in my code, the subsequent styles for the defined CSS IDs are not applied. Can someone tell me why? Here's my code:
function searchDone(results) {
var result = null;
var parent = document.getElementById('postWrap');
var child = null;
parent.innerHTML = '';
var insertHTML =" ";
//Paginating Results Links
resultNum = results.SearchResponse.Web.Total;
resultNum = resultNum/10;
child = document.createElement('div');
child.id = "paging";
if(results.SearchResponse.Web.Offset != 0){
insertHTML ='<span><a class="jsonp b" href="#" rev="'+(results.SearchResponse.Web.Offset-10)+'"><</a></span>';
}
if(results.SearchResponse.Web.Offset == 0){
insertHTML += '<span>1</span>';
}else{
insertHTML +='<span><a class="jsonp" href="#" rev="0">1</a></span>';
}
for(var i = 1; i <= resultNum; i++){
if((results.SearchResponse.Web.Offset/10) == i){
insertHTML += '<span>'+(i+1)+'</span>';
}else{
insertHTML += '<span><a class="jsonp b" href="#" rev="'+i*10+'">'+(i+1)+'</a></span>';
}
}
if(results.SearchResponse.Web.Total - results.SearchResponse.Web.Offset > 10){
insertHTML += '<span><a class="jsonp b" href="#" rev="'+(results.SearchResponse.Web.Offset+10)+'">></a></span>';
}
child.innerHTML = insertHTML;
parent.appendChild(child);
I then have some other code which processes my search query via API to Bing (only because Google now charges... )
Next, I use the same methods to insert another div:
//Insert Paginating results again
child = null;
child = document.createElement('div');
child.innerHTML = insertHTML;
child.id = "searchResultsPages";
parent.appendChild(child);
Now I'd like to apply some styles to these numbers. However, when I apply a style to searchResultsPage, like
#searchResultsPages{
float: right;
}
I don't get the style being passed on. The curious thing is that if I only insert one of these two elements, everything goes as planned and the style shows up fine. The problem is that I'd like pages displayed at the top and bottom of the search.
Any ideas why this is happening? I think it might have something to do with an element being used twice, but I don't know why this would effect anything if the objects are different.
Thanks.
child.id = "searchResultsPages";
#searchResultsPage{
See anything wrong there? :)
Like an s
IDs should be unique within the page so if you have two elements with id="searchResultsPage" the behaviour can get a bit screwy and the HTML is invalid. Instead, use a class="searchResultsPage" if there will be multiple elements.
The issue of the missing 's' the other commenters point out is also quite important though hopefully that was just a typo in the question.

How can I implement prepend and append with regular JavaScript?

How can I implement prepend and append with regular JavaScript without using jQuery?
Here's a snippet to get you going:
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.
Perhaps you're asking about the DOM methods appendChild and insertBefore.
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the
existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of
children. Equivalently, and more readably, use
parentNode.appendChild(newChild).
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element?
If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML, with appropriate first argument:
'beforebegin'
Before the element itself.
'afterbegin'
Just inside the element, before its first child.
'beforeend'
Just inside the element, after its last child.
'afterend'
After the element itself.
Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO
Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.
I added this on my project and it seems to work:
HTMLElement.prototype.prependHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
this.insertBefore(div, this.firstChild);
};
HTMLElement.prototype.appendHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
while (div.children.length > 0) {
this.appendChild(div.children[0]);
}
};
Example:
document.body.prependHtml(`Hello World`);
document.body.appendHtml(`Hello World`);
Here's an example of using prepend to add a paragraph to the document.
var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);
result:
<p>Example text</p>
In order to simplify your life you can extend the HTMLElement object. It might not work for older browsers, but definitely makes your life easier:
HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;
HTMLElement.prototype.prepend = function(element) {
if (this.firstChild) {
return this.insertBefore(element, this.firstChild);
} else {
return this.appendChild(element);
}
};
So next time you can do this:
document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:
HTMLDivElement.prototype.prepend = (node, ele)=>{
try { node.insertBefore(ele ,node.children[0]);}
catch (e){ throw new Error(e.toString()) } }
Simple arrow function that's compatible with most modern browsers.
var insertedElement = parentElement.insertBefore(newElement, referenceElement);
If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.
insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.
Examples can be found here: Node.insertBefore
You can also use unshift() to prepend to a list
document.write() is not a good practice, some browsers like Chrome give you a warning if you use it, and it may be a bad solution if you are providing it to a customer, they don't want to use your code and see warnings in the debug console!
Also jQuery may also be a bad thing if you are giving your code to a customer who already uses jQuery for other functionality on their site, there will be a conflict if there is already a different version of jQuery running.
If you want to insert content into an iframe, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

Categories

Resources