creating DOM nodes from arrays [closed] - javascript

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
Note: This is a continuation of another question that I decided were two separate issues that need to be solved. I'm also currently not sure of how exactly to phrase this question, so I will try my best and when I get more clarity I will rephrase my question for future reference.
I'm writing two basic jQuery plugins, $.fn.query and $.fn.build, that sort an array, and create html code to insert into a document, respectively. I'm currently testing it with Vimeo video ID's that I will display videos with.
$.fn.build has three parts. First it wraps every array item with individual containers, the builds them into rows (problem area), then lastly it wraps everything in a container. (every part of this is optional).
Specifically the problem comes from this line: $(tmp).add(newRow); although it is valid javascript.
if ( options.splitBy !== undefined && options.wrapRow !== undefined ) {
var tmp = $([]),
newRow = function(i) {
$(build.splice( i, i + options.splitBy )).wrapAll( options.wrapRow ).parent();
};
for (var i = 0, l = build.length, a = options.splitBy; i < l; i += a) {
$(tmp).add(newRow);
}
build = tmp;
console.log(build);
}
See: http://jsbin.com/upatus/2/edit

I am quite sure that you want to use the function, instead of adding the function itself. Also, you will want to use the same tmp object all over the time, instead of wrapping it into a new jQuery instance and not adding to the original one. Try
tmp.add(newRow(i));
BTW: If you want to build an array, you should use
var tmp = [];
and
tmp.push(…);
Now I've looked at the code from the other question. Both answers are correct, and contain some valid points:
splice is an Array function on jQuery's prototype, and returns an array. (You have fiexd this now)
Your query method returns an array, but should return a jQuery instance for chaining
Your build variable was not initialized, but used
You should really choose whether you want to use arrays or jQuery objects internally in your function, and not mix them.
BTW, you should rename your functions to more descriptive names. "build" and "query" are very vague and may collide with other plugins.

Related

How to Get Unique Elements from a DOM Collection in Vanilla JavaScript ES6+ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a JavaScript function that returns an array of Node or Element, but it contains duplicates. I searched around and found functions to get the unique items of an array, but it seems to work only on strings or simple types, when applying it to the DOM array, it does nothing. I assume it has to do with the items being objects.
Using ES6's Set as some answers suggest doesn't work. Another suggestion uses a filter function to check if the item already has an index in the array. Again, neither works for the DOM objects.
I'd appreciate it if someone could point to how I can remove the duplicates. Thanks in advance!
Update
#Kroltan seems to have understood what I mean, but for everyone else, here's a function that returns duplicate nodes:
function (
selector) {
const children = Array.from(this.parent().children).filter((
v) => v !== this);
if (!selector) {
return children;
}
return children.filter((
v) => v.matches && v.matches(selector));
}
If I were to do something like $("div"), I will get a lot of duplicates depending on nesting. I want to shrink the returned array of nodes to have no duplicates similar to how jQuery's implementation does it. Here's an example screenshot of my version (1) and jQuery's version (2). I want to get them to match.
Update 2
Figured it out. The Set solution works, but I was applying it to the wrong array and so I wasn't seeing the result I was expecting. Now that I'm applying it to the right array, it works, imagine that... :)
Those solutions do work. But they work on the principle of referential equality.
You're probably looking to remove structural duplicates, (e.g. a bunch of <br> elements or whatnot) that's trickier, and you'll have to decide on a criterion for their equality yourself. Something like Lodash's uniqBy. (check its source to see how it works!)

How to find that particular array Item is present or not Using JQuery + Backbone.js [closed]

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 6 years ago.
Improve this question
Each ArrayItem contains no. of Property like Id, Name, Description etc
But we want to Fetch ArrayItem with Help of Name Property .
So Please give me code suggestion in Jquery or backbonejs without using for loop.
If you are using BackboneJS, you already have UnderscoreJS installed. Underscore has several methods for searching through a collection. For instance, using _.findWhere(...):
var myArray = [ ... ];
var helpItem = _.findWhere(myArray, { name: 'help' });
This would return the first entry in the array that has a name property equal to 'help'. _.findWhere(...) can match multiple properties too. If you want to find an item with something other than direct equality of properties, you can use _.find(...):
var overTwentyOne = _.find(myArray, function(entry) {
return entry.age > 21;
});
This would return the first entry in the array whose age property was greater than 21.
Note also that most of the list-centric methods in Underscore are automatically mixed into all Backbone.Collection instances. So if you were searching through a Collection, the above findWhere(...) example could be more simply written as:
var helpItem = collection.findWhere({ name: 'help'});
This would return the first Backbone.Model instance from collection that had a property name equal to help.

Write a function from native javascript to jQuery [closed]

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 7 years ago.
Improve this question
I'm wondering how can I rewrite this javascript function into jQuery but using if/else statements instead of while:
<textarea style="overflow-y: hidden;" onkeyup="expandtext(this);"></textarea>
function expandtext(textArea){
while (textArea.rows > 1 && textArea.scrollHeight < textArea.offsetHeight) {
textArea.rows--;
}
while (textArea.scrollHeight > textArea.offsetHeight) {
textArea.rows++;
}
textArea.rows++
}
Well, since you appear to want it so badly, here it is
$.fn.expandText = function () {
$.each(this, function (k, textArea) {
while (textArea.rows > 1 && textArea.scrollHeight < textArea.offsetHeight) {
textArea.rows--;
}
while (textArea.scrollHeight > textArea.offsetHeight) {
textArea.rows++;
}
textArea.rows++
});
}
$('textarea').expandText();
FIDDLE
Additionally, I think I understand what you wanted to ask. In order to understand this you need a good understanding of javascript objects and document object model. There are special properties of objects in the DOM which affect how the objects are displayed (this is all done by your browser automatically), rows is one of those properties, and in order for the element on the page to change in height, which is the goal of this function, you need to change the property rows on the specific element. You can't do this with jQuery (or maybe you can, who knows) because it wraps your object in other objects. Even if it is possible, you are going to have to call a function on the wrapper object which is then going to access the DOM object and change it's property, which is what your function does in the first place, so why bother at all.

Using String/Array String as Variable name in JavaScript? [closed]

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
I'm coding a game with CraftyJS which uses JavaScript and I ran into problem where I have for loop and I need to use Variable name based on Array String... I have been trying to make it work for few hours now so I'm too tired to explain but please help me if anyone hear this!
So basicly what I'm trying to do is this:
var "TempVar"+Array[i] = Something;
also tried it whitout quotes etc... And by passing it in normal String and then using that but I didn't get it working either. If anyone know how this is supposed to do in JavaScript, or if there is alternative method please let me know that.
Sorry about my bad English, its terribly late and English is not my native language.
Also notice that I'm new to JavaScript so don't hate me too hard...
Basically youre going to need to do this:
//Create an empty object
var myObject = {};
for(var i=0; i<Array.length;i++)
{
//Add properties to the object
myObject["TempVar"+Array[i]] = Something;
}
Create an empty object and then append new properties to it within your loop. JavaScript has this neat little way properties are accessed. You can either use a dot notation like so:
myObject.property = "Blah";
Or you could access the property like an array:
myObject["property"] = "Blah";
Both perform the same operation.

Iterating through all the instances with name having a common string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Is there a way to access all the object instances starting with a common string.
Example: I have instances named button64, button223, button856471, button229846, etc. I have no control over how these instances are named. I want to push all these in an array.
I am not creating these objects, I just have to write a javascript which sits in this HTML page and collects all the object instances starting with the string 'button'.
The purpose is to reach out to a desired object out of these and change the visual element.
Also, the solution has to be compatible with IE8. Any ideas about how should I iterate?
If you can use jQuery, you could write:
var buttonsArray = [];
$("div").each(function() {
var id = $(this).attr("id");
if (id && id.indexOf("button") == 0) {
buttonsArray.push($(this));
}
});
You can use regular expressions to find any expression matching the pattern. Using the match method, every instance of the pattern is returned as an array.
var str = document.getElementById("sample");
var arr = string.match(/button[\d]*/g);
The regular expression on line two will match any result that has "button" and will stop once it encounters a character afterwards that is not a digit.

Categories

Resources