Appending duplicate javascript object - javascript

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);

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.}
}

Removing child table when appending another

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()

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/

Find any form element

I am trying to find if a class exists and if not just find the first form element. How do I write :input? This does not seem to work.
$('.focus:not(:hidden):first, :input:not(:hidden):first').focus();
Comma-separated selectors are not hierarchical in the manner you seem to indicate. Your selector will yield the first visible .focus and the first visible input element. You'll need to break this up in two selectors:
var focusElement = $('.focus:visible:first');
if(focusElement.length == 0)
focusElement = $(':input:visible:first');
focusElement.focus();
Or I suppose you could write
$('.focus:visible:first, body:not(:has(.focus:visible)) :input:visible:first').focus();
Your code actually worked for me. Take a look at this jsfiddle. Try removing my class='focus' and it then falls back to selecting the first input field.
I would go for the easy to understand model:
var finder = $('.focus:not(:hidden):first');
finder = finder.length ? finder: $(':input:not(:hidden):first');
finder.focus();
Same result, but likely better given the right to left sizzle re: performance
var finder = $('.focus').not(':hidden').eq(0);
finder = finder.length ? finder: $(':input').not(':hidden').eq(0);
finder.focus();

Easy level, selecting elements in DOM, optimization, creating method function

Please, do not laugh, too much. I know jQuery ans JS for a short a while.
1) How can I make this code more efficient? First line is how do I "select" elements, the second, line is how do I prep to "select", next or previous element.
jQuery('code:lt('+((aktywneZdanie+1).toString())+'):gt('+((aktywneZdanie-1).toString())+')').removeClass('class2');}
aktywneZdanie=aktywneZdanie-1
2) I can not create a function which is working as a method. What I meant is how to change:
jQuery('#something').addClass('class1')
.removeClass('class2');
to something like this:
jQuery('#something').changeClasses();
function changeClasses(){
.addclass('class1');
.removeClass('class2');}
For the first one, why do you need a selector like that? couldn't you find something less specific to hook onto? If you must keep it when joining an number and a string, JavaScript will convert the number to string behind the scenes so you don't really need the .toString() and could do the "maths" +/-1 outside of your selector making it more readable.
Edit
In regards to your comment I am not really sure what you mean, you could assign a class to the "post" items and then add the unique id to a data-attribute ID. To make it simpler you could do something like this:
var codeLt = aktywneZdanie + 1,
codeGt = aktywneZdanie - 1;
$('code:lt(' + codeLt + '):gt(' + codeGt +')').removeClass('class2');
End Edit
And the second solution should work, all your doing is passing the dom elements found from your selector into a function as a jQuery "array" in which manipulate to your needs
And for your second question why not just toggle the class on and off? having a default state which reflects class one?
jQuery('#something').toggleClass('uberClass');
Or you can pass your selector to the function
changeClasses(jQuery('#something'));
Then inside you function work on the return elements.
Edit
Your code should work fine, but id suggest checking to make sure you have got and element to work on:
changeClasses(jQuery('#something'));
function changeClasses($element){
if($element.length > 0) {
$element.addClass('class1');
}
}
End Edit
Hope it helps,
1) How can I make this code more efficient? First line is how do I "select" elements, the second, line is how do I prep to "select", next or previous element.
jQuery('code:lt('+((aktywneZdanie+1).toString())+'):gt('+((aktywneZdanie-1).toString())+')').removeClass('class2');}
aktywneZdanie=aktywneZdanie-1
I stoped creating this wierd code like this one above, instead I start using .slice() (do not forget to use .index() for arguments here), .prev(), .next(). Just those three and everything is faster and clearer. Just an example of it below. No it does not do anything logical.
var activeElem = jQuery('code:first');
var old Elem;
jQuery('code').slice('0',activeElem.index()).addClass('class1');
oldElem=activeElem;
activeElem=activeElem.next();
jQuery('code').slice(oldElem.index(),activeElem.index()).addClass('class1');
oldElem.toggleClass('class1');
activeElem.prev().toggleClass('class1');
and the second part
2) I can not create a function which is working as a method. What I meant is how to change:
jQuery('#something').addClass('class1')
.removeClass('class2');
to something like this:
jQuery('#something').changeClasses();
function changeClasses(){
.addclass('class1');
.removeClass('class2');}
This one is still unsolved by me.

Categories