Removing child table when appending another - javascript

Hi i am new to javascript and I am using a select element to create a table based on an array of dictionaries. I have the select element acting as a filter for the values. My problem is that when i change the value of the select element and it creates the table I want it to remove the previous table it appended so that It doesnt form a long list of tables. My on change code is as follows:
const filteredTable = document.getElementById("candidates_example");
const newFilteredTable = filteredTable.cloneNode(true);
removeRowsFromTable(newFilteredTable);
const filteredTbody = newFilteredTable.getElementsByTagName('tbody')[0];
const filterSelection = document.getElementById("filterSelect").value;
const selectFilter = filterCandidateBySkill(newCandidates, filterSelection)
addCandidatesToTable(filteredTbody,selectFilter);
document.body.appendChild(newFilteredTable);
I have tried googling the question I have but i do not know enough about javascript terminologies to know what the question is I need to ask. Thanks for any guidance offered.

You can replace the previous table with the new one using replaceChild:
replacedNode = parentNode.replaceChild(newChild, oldChild);
In your case, that would be :
document.body.replaceChild(newFilteredTable, filteredTable);

instead on append use .html() for jquery or document.getElementById('demo').innerHTML = tableVaiable;

You can use the functionality of .replaceWith() jQuery function.
.replaceWith()

Related

Problems selecting a div depending on text inside

i've been working on a project with puppeteer and it was going great so far until a tried to localize div's depending on their text.
I can't use the div id, name or class, i need to find it by the text inside of it.
My idea is to create an array of all the text i need to find and then loop trought the div's to find the ones that match any of the text in the array.
Can anybody help me find a solution? Thank you!
This is relatively straightforward using vanilla javascript (no JS libraries):
// Get an array of all <divs>:
let allDivs = [... document.getElementsByTagName('div')];
// Loop through allDivs, checking the text of each one:
allDivs.forEach((div) => {
let textInsideDiv = div.textContent;
// THE REST OF YOUR CODE HERE
// if (myArrayOfText.indexOf(textInsideDiv) > -1)) { etc.}
}

Deleting an element from JSON in javascript/jquery

I have a problem in deleting data from a JSON object in javascript. I'm creating this JSON dynamically and the removal shall also take place dynamically. Below is my JSON and the situation I'm in to.
{brands:[51,2046,53,67,64]}
Now, I have to remove 53 from this which I am calculating using some elements property, but I'm not able to remove the data and unable to find the solution for this situation. Please help me folks, thank you.
Try to use Array.prototyp.splice,
var data = { brands:[51,2046,53,67,64] };
data.brands.splice(2,1);
Since you want to remove an element from an array inside of a simple object. And splice will return an array of removed elements.
If you do not know the position of the element going to be removed, then use .indexOf() to find the index of the dynamic element,
var elementTobeRemoved = 53;
var data = { brands:[51,2046,53,67,64] };
var target = data.brands;
target.splice(target.indexOf(elementTobeRemoved),1);
You could write the same thing as a function like below,
function removeItem(arr,element){
return arr.splice(arr.indexOf(element),1);
}
var data = { brands:[51,2046,53,67,64] };
var removed = removeItem(data.brands,53);

Javascript - How to get attribute value from a tag, inside a specific div class?

Snippet of HTML code I need to retrieve values from:
<div class="elgg-foot">
<input type="hidden" value="41" name="guid">
<input class="elgg-button elgg-button-submit" type="submit" value="Save">
</div>
I need to get the value 41, which is simple enough with:
var x = document.getElementsByTagName("input")[0];
var y = x.attributes[1].value;
However I need to make sure I'm actually retrieving values from inside "elgg-foot", because there are multiple div classes in the HTML code.
I can get the class like this:
var a = document.getElementsByClassName("elgg-foot")[0];
And then I tried to combine it in various ways with var x, but I don't really know the syntax/logic to do it.
For example:
var full = a.getElementsByTagName("input")[0];
So: Retrieve value 41 from inside unique class elg-foot.
I spent hours googling for this, but couldn't find a solution (partly because I don't know exactly what to search for)
Edit: Thanks for the answers everyone, they all seem to work. I almost had it working myself, just forgot a [0] somewhere in my original code. Appreciate the JQuery as well, never used it before :-)
The easiest way is to use jQuery and use CSS selectors:
$(".elgg-foot") will indeed always get you an element with class "elgg-foot", but if you go one step further, you can use descendent selectors:
$(".elgg-foot input[name='guid']").val()
That ensures that you only get the input named guid that is a child of the element labelled with class elgg-foot.
The equivalent in modern browsers is the native querySelectorAll method:
document.querySelectorAll(".elgg-foot input[name='guid']")
or you can do what you have yourself:
var x = document.getElementsByClassName("elgg-foot")
var y = x.getElementsByTagName("input")[0];
Assuming you know it is always the first input within the div
You can combine it like this:
var a = document.getElementsByClassName("elgg-foot")[0];
var b = a.getElementsByTagName("input")[0];
var attribute = b.attributes[1].value;
console.log(attribute); // print 41
Think of the DOM as the tree that it is. You can get elements from elements in the same way you get from the root (the document).
You can use querySelector like
var x = document.querySelector(".elgg-foot input");
var y = x.value;
query the dom by selector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var fourty1 = document.querySelector('.elgg-foot input[name=guid]').value;
querySelector will return the first match from the selector. This selector will find the element with class elgg-foot and then look at the input element inside of that for one named guid and then take the value of the selected element.
I think the simplest way would be using JQuery. But using only javascript,
the simplest way would be:
var div = document.getElementsByClassName("elgg-foot")[0];
var input = div.getElementsByTagName("input")[0];
alert(input.value)
Take a look at this JSFiddle here: http://jsfiddle.net/2oa5evro/

Appending duplicate javascript object

In the following code, I'm working on a simple timer in JS. The problem is that the resulting code only shows one set of divider colons.
var divider = $('<span>').addClass('divider').text(':');
stopwatchFace = stopwatchFace.append(timeHour).append(divider)
.append(timeMin).append(divider).append(timeSec);
Is there a reason why the first one isn't being picked up? Should I be explicitly defining a divider1 and a divider2 object?
If you append an already-appended element, the result is that it is moved.
You need to clone the element. In vanilla JS, this would be as simple as divider.cloneNode(true).
In jQuery it's simple too: divider.clone(). Thanks Boaz for the info ^_^
Use need to clone divider. as divider is a dom single element cant exist two place at same time.
var divider = $('<span>').addClass('divider').text(':');
stopwatchFace = stopwatchFace.append(timeHour).append(divider.clone())
.append(timeMin).append(divider).append(timeSec);

Can I get a jQuery object from an existing element

I have a function
function toggleSelectCancels(e) {
var checkBox = e.target;
var cancelThis = checkBox.checked;
var tableRow = checkBox.parentNode.parentNode;
}
how can I get a jQuery object that contains tableRow
Normally I would go $("#" + tableRow.id), the problem here is the id for tableRow is something like this "x:1280880471.17:adr:2:key:[95]:tag:". It is autogenerated by an infragistics control. jQuery doesn't seem to getElementById when the id is like this. the standard dom document.getElementById("x:1280880471.17:adr:2:key:[95]:tag:") does however return the correct row element.
Anyways, is there a way to get a jQuery object from a dom element?
Thanks,
~ck in San Diego
Absolutely,
$(tableRow)
http://docs.jquery.com/Core/jQuery#elements
jQuery can take the DOM elements, try with:
$(tableRow)
or
$(checkBox.parentNode.parentNode)
You should be able to pass the element straight in, like this:
$(tableRow)...
I have tested this by creating a reference to a div, then passing it straight into jQuery and it creates the jQuery object for you.
You can call the jQuery function on DOM elements: $(tableRow)
You can also use the closest method of jQuery in this case:
var tableRowJquery = $(checkBox).closest('tr');
If you want to keep using your ID, kgiannakakis (below), provided an excellent link on how to escape characters with special meaning in a jQuery selector.
See this for how you should escape the id.
try:
var r = $(document.getElementById("XXXX----ID Of Your Row----XXXX"));
now, if document.getElementById doesn't return undefined you can use r as any regular jquery object.

Categories