Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to clone a section on a HTML page on user click.
In a form, I'm trying to copy and add a field group, when user wants to add more elements to the form.
While cloning, I want to make sure all the ids are rewritten so that the page and elements are intact.
I've been thinking about a neat way of doing this.
Trying the following approaches.
Am more in favour of JQuery because of the compactness and beauty in the expression.
Would love to hear some perspectives from experts.
JS Approach:
function addElementToParentById(src) {
var temp = document.getElementById(src);
var tempParent = temp.parentElement;
var tempNew = temp.cloneNode(true);
renameIds(tempNew,"1");
tempParent.appendChild(tempNew);
}
function renameIds(param, token) {
if(param.id){
param.id=param.id+token;
}
for(i =0; i < param.childNodes.length; i++) {
var tempChild = param.childNodes[i];
if(tempChild.id) {
tempChild.id = tempChild.id + token;
}
if(tempChild.childNodes
&& tempChild.childNodes.length > 0) {
for(j =0; j < param.childNodes.length; j++) {
renameIds(tempChild.childNodes[j], token);
}
}
}
}
Jquery approach:
$("#addbtnid").click( function() {
$("#filopsmainpane").append($("#filopspane").clone(false).find("*[id]").andSelf().each(
function() { $(this).attr("id", $(this).attr("id") + "1"); }));
}
"Best" is subjective, but I prefer using a framework (for example jQuery) because:
Shorter code is less likely to contain an error and is easier to maintain
The framework's authors have already done the work to deal with browser inconsistencies
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Hey guys im developing something and I need to fix this please give me some feedback on how to improve this. (how to make it cleaner, easier to read , etc). Here's the code!
function wordFliper(word) {
let wordOutput = "";
let reverseIndex = word.length - 1;
for (let index = reverseIndex; index >= 0; index--) {
let storage = word[index];
wordOutput = wordOutput + storage;
}
return wordOutput;
}
I would remove some variables (variables that are used once in loop and then assigned to a function variable) to reduce code and rename one like this:
/// <summary>Function to flip words backwards</summary>
/// <param name="word" type="string">Word to be flipped</param>
/// <returns type="string">Word flipped</returns>
function wordFlipper(word) {
let flippedWord = "";
for (let i = word.length - 1; i >= 0; i--) {
flippedWord += word[i];
}
return flippedWord;
}
Also IMHO use i variable instead of index (for loop incrementer)
And Also get used to commenting your code, to know what is for the functions you're writing
I hope you helped to keep your code clean for further programming and happy coding!
You can use JS array functions like reduce(),split(),reverse(), etc. You can write the code in following ways:
function wordFlipper(word) {
return(word.split('').reverse().join(''));
}
function wordFlipper(word) {
return(word.split('').reduce((a,c)=>c+a));
}
Please go through the links for clarity on the functions used above:
split() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
join() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
reverse() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
reduce() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So for example if I have this array:
var input = [1,1,2,4,6,7,7,1];
I want the output to be something like:
[1,2,1,4,6,7,1,7]
The order of the new array does not matter, as long as similar items will never (or at least as seldom as possible) neighbor each other.
I can use plain JavaScript as well as underscore.js.
Try the following:
var input = [1,1,2,4,6,7,7,1];
input.sort()
var output = [];
var len = input.length;
for (var i = 0; i < Math.floor((len / 2)); i++) {
output.push(input[i]);
output.push(input[len - i - 1]);
}
if (len % 2) {
var left_over = input[Math.floor(len / 2)];
if (left_over == output[0]) {
output.push(left_over);
} else {
output.unshift(left_over);
}
}
Or see http://jsfiddle.net/d0j3Lfa3/1.
The solution sorts the numbers then alternates high and low. It deals with an odd number of elements, including corner cases such as [1,1,2] and [1,2,2] where it needs to push the middle element differently to pass. Since the input is sorted, input order doesn't affect the output.
This answer may help simplify things a bit.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Translated (apparently wrongly) from a C++ book.
If I can get it to work, then I can start trying to understand it.
function recPermute(soFar, rest)
{
if (rest==="")
{
console.log(soFar);
}
else
{
for(i=0; i<rest.length; i++) // <<< error was in not declaring the "i"
{
var next = soFar + rest[i];
var remaining = rest.substr(0,i) + rest.substr(i+1);
recPermute(next, remaining);
}
}
}
function listPerm(s)
{
recPermute("",s);
}
listPerm("kitcap")
You need to declare i so it's scoped to recPermute:
for(var i=0; i<rest.length; i++)
Without the var, it'll be created as a global so each call to recPermute will alter it for any other calls.
for JavaScript, use charAt(), instead of using array like acessing.
var next = soFar + rest.charAt(i);
One thing that could be an issue is you are using effectively the same i for each call to the function. You need to declare a local i or it will be declared in the global scope.
for(var i = 0; ....
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So if I make a class, and then create new instances of that class without naming them -maybe with a loop that creates a bunch of instances- how can I call a specific (or unspecific) instance? For example, if I'm generating a bunch a squares, but I want to move a specific one somewhere, how would I do that?
Sorry if this is a total noob question, or if I miss-used some terminology, but I'm pretty new to programming.
Example code:
function example(x){
this.x = x;
}
for(var i=0; i<10; i++){
new example(1);
}
//now how would I get a specific instance of examples to have x = say, 10.
You could put each square in an array and access them that way:
function Square(i){
this.index = i;
}
Square.prototype = {
constructor: Square,
intro: function(){
console.log("I'm square number "+this.index);
}
}
var squares = [];
for(var i = 0;i < 10;i++){
squares.push(new Square(i));
}
squares.forEach(function(square){
// do something with each square
square.intro();
});
Demo: http://jsfiddle.net/louisbros/MpcrT/1/
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
a javascript+DOM question.
Can someone improve my code?
I have a page nav bar like this (on some pages):
<div id="pagebar">
1
2
3
4
5
6
</div>
I want my javascript to change the link style so that the style of the current page is highlighted.
My javascript code is this. It finds the current page's url, then try to match it with one of the link tag. If match, then set style.
function setPageBarStyle() {
var pageNavBar = document.getElementById("pagebar");
if (pageNavBar != null) {
var fPath = document.location.pathname;
var fPathParts = fPath.split('/');
var fName = (fPathParts[fPathParts.length-1]); // file name after last slash. e.g. xyz.html
var linkTags = pageNavBar.getElementsByTagName("a");
for (var ii = 0; ii < linkTags.length; ii++) {
var aUrl = linkTags[ii].href;
var aUrlParts = aUrl.split("/");
var aUrlLastPart = (aUrlParts[aUrlParts.length-1]); // part after last slash. e.g. xyz.html
if (aUrlLastPart == fName) {
linkTags[ii].style.border="thin solid blue";
}
}
}
}
setPageBarStyle();
How can i improve the code? I am new to DOM scripting.
The way i split the path seem too verbose, with many variables. I think it can be done with regex, but don't know how with javascript/DOM.
Thanks.
You can change this:
var aUrl = linkTags[ii].href;
var aUrlParts = aUrl.split("/");
var aUrlLastPart = (aUrlParts[aUrlParts.length-1]); // part before last slash. e.g. xyz.html
With this:
var aUrlLastPart = linkTags[ii].href.split("/").pop();
The Pop() method will return the last element of the array returned by split() and remove it from the array (which in your case, is irrelevant).
I would also recommend checking out jQuery or similars, in order to manage cross browser JS easier...
Let me know if it helps! :)