I have a function clearBoth where I grab all elements with class 'clear' and remove them. However I
would like to keep 2 of them. Right now I get rid of all elements with a class 'clear' and then create
again 2 which I assume is not a very good solution.
function clearBoth(postContent) {
var clearElem = document.querySelector('.clear');
if(typeof(clearElem) !== "undefined" && clearElem !==null) {
document.querySelectorAll('.clear').forEach(function(a) {
a.remove()
})
var clearBoth1 = document.createElement('br');
clearBoth1.className = 'clear';
postContent.insertAdjacentElement("beforeend", clearBoth1 );
var clearBoth2 = document.createElement('br')
clearBoth2.className = 'clear';
postContent.insertAdjacentElement("beforeend", clearBoth2);
} else {
var clearBoth3 = document.createElement('br')
clearBoth3.className = 'clear';
postContent.insertAdjacentElement("beforeend", clearBoth3);
var clearBoth4 =
document.createElement('br')
clearBoth4.className = 'clear';
postContent.insertAdjacentElement("beforeend", clearBoth4 );
}
}
Why not try using a combination of :not and an nth-range? This will select every element with the exception of the last two:
document.querySelectorAll('.clear:not(:nth-last-child(-n+2)');
Additionally, your forEach will not work. Reason being, you're trying to invoke an array based method when in reality you have an HTMLCollection. You'll have to convert the collection using a bevy of options: Array.from or call or spread syntax:
NodeLists do in fact have their own forEach but by user request I left this solution here in the event an HTMLCollection needs to access methods from the Array.prototype:
Array.from()
Array.from(document.querySelectorAll('.clear:not(:nth-last-child(-n+2))')).forEach(...);
call
Array.prototype.forEach.call(document.querySelectorAll('.clear:not(:nth-last-child(-n+2))')).forEach(...);
Spread Syntax
[...document.querySelectorAll('.clear:not(:nth-last-child(-n+2))')].forEach(...);
Related
I have an object declared, and I have an html form with some matching fields.
All fields in the form are in the object, but the object also has a couple of additional variables and functions.
I'd like to fill the object with the data entered in the form, what I'm trying right now overwrites the declared object, and so doesn't have the functions nor the other variables.
The object :
var Container = {
nodes: [],
Contains: function (Node) {
for (var i = 0; i < this.nodes.length; i++) {
if (this.nodes[i].nodeID === Node.nodeID)
return (i);
}
return (-1);
}
How I fill it from the form :
const handleContainerForm = event => {
event.preventDefault();
ContainerFormToJSON(form.elements);
var i = JSONData.Contains(Container);
if (i === -1)
JSONData.containers.push(Container);
else
JSONData.container[i] = Container;
output = JSON.stringify(JSONData, null, " ");
displayContents(output);
};
The form has ID, Title, Folder, Image and Description as fields, so this last Container object doesn't have the Contains() function nor the nodes[] array.
How do I end up with a complete, filled version of the object I have declared ?
In ContainerFormToJSON function, before the statement
return Container
define:
//container.nodes and container.contains
You are right, JavaScript is very different from C#, especially in regards to OOP. But that doesn't make it better or worse.
In JavaScript, you don't need to declare an object's properties, like you have to when you use classes. I think that you only want to serialize the form's input values to JSON. I recommend not to use an object that additionally has a nodes property and a Contains method.
If you need to keep a copy of the unserialized object, create two objects:
class Container {
constructor () {
this.nodes = [];
}
indexOf (node) {
return this.nodes.findIndex(n => n.nodeID === node.nodeID);
}
}
Container.nodeID = 0; // think of it as a static property
function extractValues (elements) {
// 'elements' is an array of <input> elements
// the 'container' will be filled and serialized
var container = new Container();
for (var index in elements) {
var element = elements[index];
container[element.name] = element.value;
}
container.nodeID = Container.nodeID++; // give the container a unique ID
return container;
}
var inputs = document.querySelectorAll('input');
var jsonData = new Container();
document.querySelector('button').addEventListener('click', function () {
var newContainer = extractValues(inputs);
var index = jsonData.indexOf(newContainer);
if (index === -1) {
jsonData.nodes.push(newContainer);
} else {
jsonData.nodes[index] = newContainer;
}
var jsonString = JSON.stringify(jsonData, null, ' ');
console.log(jsonString);
});
<input name="containerID">
<input name="containerTitle">
<!-- ... -->
<button>Serialize</button>
Please note: only setting an object's properties doesn't make it to JSON. It's only JSON if it's serialized to a string. I recommend this article. To serialize a JavaScript object, use JSON.stringify.
Edit:
Looking at the edit of your question, I think it might be preferable to create a Container class. Both jsonData and the containers of the form data will be instances of that class. It can contain other containers (nodes), and can get the index of such a nested container using the indexOf method. I implemented this in the above code snippet. Whenever you hit the "Serialize" button, a new container with the current <input>s' contents will be added to jsonData. The JSON form of jsonData will be logged to the console.
I hope this is what you are looking for. To better understand JavaScript OOP,
take a look at some of the articles at MDN.
the problem is that I have multiple objects with the same id. As you can see this works when it comes to removing all the items with the same id. How I can remove the objects one by one no matter if they are the same ID...thanks
individualObjects:[],
actions:{
increment:function(){
var obj = this.get('object');
this.get('individualObjects').pushObject(obj);
},
decrement:function(){
var obj = this.get('object');
var filter = this.get('individualObjects').findBy('obj_id', obj.get('obj_id'));
this.get('individualObjects').removeObject(filter);
}
}
Well to filter array you would need to use Array.filter to find out the items that do not belong in the "individualObjects" and later simply remove them by using "removeObjects"
decrement:function(){
var objects = this.get('individualObjects')
var notWanted = objects.filterBy('obj_id', this.get('object.obj_id'));
this.get('individualObjects').removeObjects(notWanted);
}
and solution 2
decrement:function(){
var removeObj = this.get('object');
var objects = this.get('individualObjects')
// As the condition is true given object is returned
var notWanted = objects.filter(obj => { return obj.get('obj_id') === removeObj.get('obj_id') });
this.get('individualObjects').removeObjects(notWanted);
}
Ok so you want to remove items one by one. Weird but can be accomplished
first get the length for
var notWantedCount = objects.filterBy('obj_id', this.get('object.obj_id')).length;
Now
for(var i=0; i <= notWantedCount; i++) {
var toRemove = individualObjects.findBy('obj_id', obj.get('obj_id'));
individualObjects.removeObject(toRemove);
// Make some custom actions one by one.
}
I don't know ember, but you'll want to do a foreach on the array, and then test for id on each one. It should be something like this:
decrement:function(){
var obj = this.get('object');
self = this;
this.get('individualObjects').each(function(individualObject) {
if (individualObject.get('obj_id') == obj.get('obj_id'))
... you want to do something here? ...
self.get('individualObjects').removeObject(individualObject);
}
}
That way you can remove each object individually. Running any necessary code before or after it's removed. If you want to sort it first, you can do that before running the each function.
So I'm working on a little personal project and I came upon a problem.
I need each day object to hold various dom element objects. These object instances are stored in an array and then that array needs to be stored into localStorage to load later.
The problem is when I do JSON.stringify and then JSON.parse it converts the HTML nodes into objects. So when I try to append element it tells me that the first parameter is not a node.
function save() {
localStorage.days = JSON.stringify(global.days);
localStorage.numberOfDays = global.numberOfDays;
localStorage.totalCount = global.totalCount;
}
function load() {
var parsedDays = JSON.parse(localStorage.days);
parsedDays.forEach(function(day){
document.getElementById("mainPage").appendChild(day.textObject);
});
anyone know how I can put an array of objects which hold elements into localStorage while keeping their node type????
If you will try to stringify dom nodes then it will return "{}".So its not possible to store node as it is inside localstorage.
What you can do is store information regarding nodes inside localstorage and recreate your node from that information and add it in your dom.
You'd probably need to have a property eg 'type' that defines the element type
var elem
parsedDays.forEach(function(day){
elem = document.getElementById("mainPage").createElement(day.type);
elem.attributes = day.attributes;
elem.innerHTML = day.textObject;
});
Or something like that, not too sure without seeing your day object
Use JSON.stringify and JSON.parse
Example Code:
Element.prototype.toJSON = function (){
return {nodeType:this.nodeType, outerHTML:this.outerHTML};
};
function replacer(k,v){
if(v.nodeType===1 && v.outerHTML){
var ele = document.createElement('html');
ele.innerHTML = v.outerHTML;
return ele.removeChild(ele.firstChild);
}
return v;
}
//test
var jstr = JSON.stringify({ele:document.body});
var json = JSON.parse(jstr,replacer);
console.log(jstr);
console.log(json);
I have a few divs that I'd like to put into an array.
When I try to use jQuery.inArray(), my div (as a jQuery object) isn't found. Why not?
var myArray = [ $("#div1"), $("#div2"), $("#div3") ];
alert(jQuery.inArray($("#div1"),myArray)); // returns -1
$ creates a new jQuery collection object each time, so var a = $("div"), b = $("div") will actually be two different objects that don't equal each other.
Instead you can just use the selectors or some other identifying feature of the element.
var myArray = ["#div1", "#div2", "#div3"];
However it really depends on your use case.
Two objects are never the same, so when you do
var object1 = $('#div1');
var object2 = $('#div1');
even if you have the same element, the objects are not the same
If you use the same object, it works
var div1 = $('#div1');
var div2 = $('#div2');
var div3 = $('#div3');
var myArray = [ div1, div2, div3 ];
jQuery.inArray( div1 , myArray); // returns 0
You can't use .inArray() for object comparison by content.
I like the approach outlined here. It's very clean.
It's probably because each invocation of the jQuery constructor results in a new instance referring to the same DOM node. What would effectively allow you to demonstrate inArray looks something like this:
var $div1 = $('#div1'),
$div2 = $('#div2'),
myArray = [ $div1, $div2 ];
alert(jQuery.inArray($div1,myArray));
You are not storing any references to the jQuery objects, $("#div1") will return a new jQuery object containing your dom element, you are comparing two different jQuery objects containing the same dom element. inArray will work just fine if you are using the same reference in the array as when you do use the inArray method.
var arr = [],
$d1 = $("#d1"),
$d2 = $("#d2"),
$d3 = $("#d3");
arr.push($d1, $d2, $d3);
console.log(jQuery.inArray($d3, arr));
or see http://jsfiddle.net/EQQ96/2/
You're better off creating an array of ids. When it you roll, you can then see if that id is in your array, and then move forward.
var possiblePositions = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
function randomSpin(sides) {
return Math.floor(Math.random() * (sides || 6) ) + 1;
}
var $currentPiece = $('piece.active');
var currentSpot = $currentPiece.attr('spotPosition');
var spin = randomSpin(6) + randomSpin(6);
var nextSpot = currentSpot + spin;
if (possiblePositions.indexOf(nextSpot)) {
$('#div' + nextSpot).append($currentPiece);
}
If you were to use purely jQuery to manipulate the jQuery Collection then you can use the jQuery index() method. However, the index returned is the position of the element in the dom, not the order in which it was added to the collection. If you need to deal with the order of adding then you're better of using selector strings rather than jQuery Collection:
var myArray = $([]).add( "#div4" ).add( "#div3" ).add( "#div1" ).add( '#div2' );
console.log( myArray.index( $('#div3') ) ); //Output: 2
JS FIDDLE DEMO
I would like to create element in Jquery/Javascript by using "div.someelement" like this
var SomeElement = $("div.someelement");
$( "#container" ).append( SomeElement );
But I don't want to copy element with the same class, I would like to create new one.
document.createElement is creating "<div.somelement>" instead of <div class="someelement">
I would use the following method to create elements on the fly
$("<div/>",{
"class" : "someelement",
// .. you can go on and add properties
"css" : {
"color" : "red"
},
"click" : function(){
alert("you just clicked me!!");
},
"data" : {
"foo" : "bar"
}
}).appendTo("#container");
Try this:
var $someelement = $('<div class="someelement"/>').appendTo('#container');
This will create a brand new element inside of #container and save it as $someelement for easy reference later.
http://api.jquery.com/jQuery/#jQuery2
UPDATE
You could clone the original then empty it out. This doesn't affect the original element at all.
var $someelement = $('div.someelement').clone().empty().appendTo('#container');
You can do this by the following:
var newElement = $('<div class="someelement"></div>');
$('#container').append(newElement);
or if you don't need the element you can directly append it:
$('#container').append('<div class="someelement"></div>');
According to the question you want to use a syntax like "div.someelement" to create an element.
In order to do that, you need to make your own parser.
It is very simple if that will be the exact syntax.
var str = "div.someelement",
parts = str.split("."),
elem = $("<" + parts.shift() + ">"),
cls;
while (cls = parts.shift())
elem.addClass(cls);
But if you're going to do this, you might as well use native methods.
var str = "div.someelement",
parts = str.split("."),
elem = document.createElement(parts.shift());
elem.className = parts.join(" ");
If you want to allow for full CSS syntax for creating an element, then you may want to look at the regex parser that Sizzle uses, and use it for your needs.
Use this:
var someElement = $("<div></div>");
someElement.addClass("someelement");
$("#container").append(someElement);
Or you can chain together the calls:
$("#container").append(
$("<div></div>")
.addClass("someelement")
);
EDIT:
Perhaps I misunderstood the question, maybe this will help. To create a new set of elements, use jQuery's clone method:
$("div.someelement").clone().appendTo("#container");
I would use zen coding for textarea as a starting point. Its syntax is close enough for what you are trying to do, its a well understood implementation. You should be able to invoke the transformation from a raw string rather than from a textarea with a little tweaking.
Since you are asking about creating an element from css syntax, you need to use a parser to interpret the syntax.
Here is an example you can build from. This will match an element name followed by id, class or other attributes. It won't cover some edge cases, but will work in most cases.
var elem_regex = /^(\w+)?|(#|\.)([^.#\[]+)|(\[[^\]]+?\])/g
Then make a function to get the parts and create an element.
function elementFromSelector(str) {
var match, parts = {}, quote_re = /^("|').+(\1)$/;
while (match = elem_regex.exec(str)) {
if (match[1])
parts.name = match[1];
else if (match[2] === ".") {
if (!parts.clss)
parts.clss = [];
parts.clss.push(match[3]);
} else if (match[2] === "#")
parts.id = match[3];
else if (match[4]) {
var attr_parts = match[4].slice(1,-1).split("="),
val = attr_parts.slice(1).join("");
parts[attr_parts[0]] = quote_re.test(val) ? val.slice(1,-1) : val;
}
else throw "Unknown match";
}
if (parts.name) {
var elem = document.createElement(parts.name);
delete parts.name;
for (var p in parts)
if (p === "clss")
elem.className = parts[p].join(" ");
else
elem[p] = parts[p];
return elem;
} else throw "No element name at beginning of string";
}
Then pass a proper string to the function, and it will return the element.
var str = 'input#the_id.firstClass.secondClass[type="text"][value="aValue"]';
var element = elementFromSelector(str);
Before creating the element, the parts look like this.
{
"name": "input",
"id": "the_id",
"clss": [
"firstClass",
"secondClass"
],
"type": "text",
"value": "aValue"
}
Then it uses that info to create the element that gets returned.
Simply create a new Element for jQuery:
var $newElement = $(document.createElement("div"));
$newElement.appendTo($("body"));
if you want to at attributes to de element simplie use:
$newElement.attr({
id : "someId",
"class" : "someClass"
});
Rember by class always use like this "class", because class is a reserved name