Remove existing code side of div code - javascript

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 = ''

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

getElementById throwing an error when trying to append while looping through a HTMLcollection

I was trying to append some dynamically created html. It throws an error while using getElementById. .audit-table-element is a div in DOM with that particular class.
<div class="audit-table-element"></div>
Javascript :
var elems = document.getElementsByClassName('audit-table-element');
for(var i = 0; i < elems.length; i++) {
elems[i].getElementById("always-audit-table" + category.id + "")
.getElementsByTagName("tbody")[0]
.insertAdjacentHTML("beforeend", auditTableRow);
}
Error - TypeError: elems[i].getElementById is not a function
When I remove the line getElementById("always-audit-table" + category.id + ""), appending is working, but gets appended at the wrong place. So i need to have that line for the HTML to be appended at the right place
You can use querySelector instead of getElementById. Your code should be like below.
elems[i].querySelector("[id = always-audit-table" + category.id + "]")
.getElementsByTagName("tbody")[0]
.insertAdjacentHTML("beforeend", auditTableRow);
querySelector : These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc.
Click here to learn more about querySelector
I don't know how your code looks like, but i try to create one example here. have a look to this, your doubts will be cleared out
var testRow = "<tr><td>Data 1</td><td>Data 2</td></tr>";
var ele = document.getElementsByClassName('test');
for(var i = 0; i < ele.length; i++){ debugger;
ele[i].querySelector("[id = id"+i+"]").getElementsByTagName("tbody")[0].insertAdjacentHTML("beforeend", testRow);
}
<div class='test'>
<div id='id0'>
<table><tbody></tbody></table>
</div>
</div>
<div class='test'>
<div id='id1'>
<table><tbody></tbody></table>
</div>
</div>

Deleting the last Element in a Div [JavaScript]

I'm having a strange problem. I'm trying to make a program that will add and delete div's inside another div called "body". To add divs, I use document.getElementById("body").innerHTML. Adding works fine. However, in the deleting function, I replace the "body" id with a variable with the id of the div that will be deleted. But when I run the code, I get the error "cannot set innerHTML of null". I tried to replace the id variable with a fixed local variable, and it worked fine. I also tried to add quotes to the variable but that didn't work either. Is there any reason why I can't set the id to a changing variable? Thanks.
Here is my code:
var i = 1;
function myFunction() {
var addDiv = document.getElementById("body2");
addDiv.innerHTML += "<div id = '" + i + "'><br><textarea id = '1' > foo < /textarea></div > ";
i++;
}
function myFunction2() {
var deleteDiv = document.getElementById(i);
deleteDiv.innerHTML = "";
i--;
}
<div id="body2">
<div id="0">
<textarea id="text">lol</textarea><button onclick="myFunction()">Add</button>
<button onclick="myFunction2()">Delete</button>
</div>
</div>
you are incrementing i after adding a div so you must use i-1 while deleting to get correct id.
var i = 1;
function myFunction() {
var addDiv = document.getElementById("body2");
addDiv.innerHTML += "<div id = '"+i+"'><br><textarea id = '1'>foo</textarea></div>";
i++;
}
function myFunction2() {
var deleteDiv = document.getElementById(i-1);
deleteDiv.remove();
i--;
}
<div id = "body2">
<div id = "0">
<textarea id = "text">lol</textarea><button onclick =
"myFunction()">Add</button>
<button onclick = "myFunction2()">Delete</button>
</div>
</div>
To remove last child, you can even use CSS selector last-child. You should also add specific class to newly added divs as you would want to remove only newly added divs.
This will also remove dependency of i.
As an addon, you can also use document.createElement + Node.appendChild instead of setting innerHTML. .innerHTMl will be expensive for highly nested structure.
function myFunction() {
document.getElementById("body2").appendChild(getDiv());
}
function getDiv(i){
var div = document.createElement('div');
div.classList.add('inner')
var ta = document.createElement('textarea');
ta.textContent = 'foo';
div.appendChild(ta);
return div;
}
function myFunction2() {
var div = document.querySelector('#body2 div.inner:last-child')
div && div.remove()
}
<div id="body2">
<div id="0">
<textarea id="text">lol</textarea><button onclick="myFunction()">Add</button>
<button onclick="myFunction2()">Delete</button>
</div>
</div>
You can refer "innerHTML += ..." vs "appendChild(txtNode)" for more information.

Vanilla Javascript equivalent of jQuery not()

This is what I'm doing in jQuery:
var text2 = $(node).not("span").text();
console.log(text2);
How do I do this same thing in pure javascript?
I know how to get elements in javascript, but not how to ignore elements and select the rest
var spans = node.getElementsByTagName('span');
I need to get every elements within node that does not contain a <span>
Here is my HTML
<tr>
<td>
<span>Farley</span>
<div class="table-row__expanded-content">
<data-key>Sex: </data-key> <data-value>Male</data-value><br />
<data-key>DOB: </data-key> <data-value>12/08/2010</data-value> <br />
<data-key>Weight: </data-key> <data-value>20 lbs</data-value> <br />
<data-key>Location: </data-key> <data-value>Kennel 2B</data-value> <br />
<data-key>Temperament: </data-key> <data-value>Aggresive</data-value> <br />
<data-key>Allergies: </data-key> <data-value>Sulfa, Penicillin, Peanuts</data-value>
</div>
</td>
<td>Cunningham, Stephanie</td>
<td>Dog</td>
<td>Pomeranian</td>
<td>PQRST1234567</td>
</tr>
Or a quick example that runs in a console on this page:
var startNode = jQuery("li.related-site").get(0); // quick jQ to get a testable node.
var spanLess = [];
var child = startNode.firstChild;
while(child){
if(child.nodeType == 1){
var anySpans = child.getElementsByTagName('span');
if(!anySpans.length) spanLess.push(child);
}
child = child.nextSibling;
}
spanLess;
Based on your comment that you are trying to extract values for use with tablesorter what you might also find useful is a function to extract the text values from a node regardless of markup:
function extractText(node){
if(node.nodeType == 3) return node.nodeValue.trim();
if(node.nodeType == 1){
var buf = [];
var child = node.firstChild;
while(child){
var val = extractText(child);
if(val) buf.push(val);
child = child.nextSibling;
}
return buf.join(' ');
}
return '';
}
Try querySelectorAll
var notSpans = document.getElementsByTagName('div')[0].querySelectorAll(':not(span)');
for (var i = 0; i < notSpans.length; i++) {
notSpans[i].style.color = 'green';
}
<div>
<p>not a span</p>
<span>a span</span>
</div>
Thanks to bknights, I was able to modify his answer to work for my needs.
My full fuction is as follows:
var myTextExtraction = function (node) {
//console.log(node);
var child = node.firstChild;
while (child) {
if (node.getElementsByTagName('span').length) {
childValue = child.nextSibling.innerHTML;
console.log(childValue);
}
else {
childValue = child.nodeValue
console.log(childValue);
}
return childValue;
}
}
Then I create the node object with the tablesorter plugin:
// Load the table sorter
$(".table").tablesorter(
{
textExtraction: myTextExtraction
}
);
This loops through and outputs the text inside <td><span>mytext</span></td> as well as the text in <td>myothertext<td>. I'm using this for the jquery TableSorter plugin to work with complex data inside <td>s

find difference in two dom elements then make them same

If I have two elements :
Element A :
<div id="myID">
<div id="a"></div>
<div id="b"><div id="ba"></div></div>
<div id="c"><span id="ca"></span></div>
</div>
and Element B :
<div id="myID">
<div id="a"></div>
<div id="b"><div id="ba"></div></div>
<div id="c"><span id="ca"></span></div>
<div id="d"></div>
</div>
Is it possible to find out that Element B has more children than Element A, then find where is additional element and create it in Element A?
P.S: In real code new element is loaded with Ajax Request, but I don't want to replace all content with loaded content, I need to add only new content and skip existing one.
P.S.S : In my current code I have Md5 checksum to check if new content is not the same as existing, but if new content have only little changes it replaces all content and this is the problem for me.
A piece of my current code :
window.processResponse = function(data) {
// Note : "data" is Ajax responseText;
if(!data) return false;
var $data = document.createElement("div");
$data.innerHTML = data;
var em = $data.getElementsByTagName("*");
for(var i = 0; i < em.length; i++)
{
var parent = sget(em[i].id); // sget function is : document.getElementById
if(parent)
{
var html = em[i].innerHTML.replace(/(\s)+/gim, "").replace(/(\n|\r\n)+/gim, "");
var id = em[i].id;
savedPages[id] = savedPages[id] || [];
var _md5 = md5(html);
if(savedPages[id][0] == _md5) continue;
savedPages[id] = [_md5, getTime()];
parent.innerHTML = em[i].innerHTML;
}
if(em[i].tagName === "SCRIPT")
{
var code = em[i].innerHTML.replace(/(\s)+/gim, "").replace(/(\n|\r\n)+/gim, "");
var id = em[i].id;
savedPages[id] = savedPages[id] || [];
var _md5 = md5(code);
if(savedPages[id][0] == _md5) continue;
savedPages[id] = [_md5, getTime()];
try{eval(em[i].innerHTML)}catch(ex){log(ex)};
}
}
};
So, you can optimize it but it depends also in which browser are you running this code.
I assumed the follows:
All IDs are unique, and you rely on that. You want to compare basically elements that have the same ID, not the same structure.
As you said, all children have IDs, and you want to compare only children – not nested node
The elements received from the server have only additional children not less. For removing children, you have to add some other code.
Therefore, if you have the same number of children, we assume they're the same (to optimize). If this is not true, then you have to implement the removal of children as well
Said that, I believe that this kind of stuff is more suitable on server side, that should send to the client only the part that are actually modified. That what we do usually – or, if we don't care, replace everything.
var div = document.createElement('div');
div.innerHTML = s;
var root = div.firstChild;
var children = root.children;
var documentRoot = document.getElementById(root.id);
if (documentRoot && documentRoot.children.length < children.length) {
var node = null;
var previousNode = null;
var index = 0;
while ( node = children[index++] ) {
var documentNode = document.getElementById(node.id);
if (!documentNode) {
if (previousNode)
documentRoot.insertBefore(node, previousNode.nextSibling);
else
documentRoot.insertBefore(node, documentRoot.firstChild);
documentNode = node;
}
previousNode = documentNode;
}
previousNode = null;
} else {
// probably append as is somewhere
}
The solution is not so simple. What if the parent, myID, did not exist in sample A but the child nodes were in both samples indicating 3 layers in the DOM that need to be compared and adjusted? How would you compare this:
<div id="papa">
<div id="myID">
<div id="a"></div>
<div id="b">
<div id="ba"></div>
</div>
<div id="c">
<span id="ca"></span>
</div>
</div>
</div>
vs
<div id="papa">
<div id="a"></div>
<div id="b">
<div id="ba"></div>
</div>
<div id="c">
<span id="ca"></span>
</div>
</div>
In this case the comparison becomes more complicated. You will actually need a fully fleshed out XML/HTML language aware diff utility with a merge function. You can play around with Pretty Diff to demonstrate just how complicated this can get, but unfortunately it does not have a merge function so it cannot be a fully automated solution to your problem.

Categories