Combining jQuery with native JS in DOM creation - javascript

I'm reusing an old application of mine and want to change the code so I'm applying the DOM structure that I build up to a node's class instead of it's id.
Below is a piece of the code and as you can see I try to combine jQuery (getting the node by it's class) with the old structure, but something doesn't work properly here.
Is it possible to combine jQuery and JS native like this?
If not, is there another way to accomplish what I want to do?
var gamearea = $('<div/>', {
text': 'testarea',
class': 'gamearea'
}).appendTo('.memory:last');
alert("this.rows: " + this.rows);
for (var j = 0; j < this.rows; j++){
var box = document.createElement('div');
for (var i = 0; i < this.cols; i++){
var iterator = (this.cols * j) + i;
var img = document.createElement('img');
var aNod = document.createElement('a');
aNod.href = "#";
img.src = "pics/0.png";
aNod.appendChild(img);
box.appendChild(aNod);
}
gamearea.appendChild(box);
}

You should be able to get it working by changing gamearea.appendChild(box); to gamearea[0].appendChild(box);
The reason behind that is you can get the bare DOM element for a jQuery extended object by simply doing obj[0], where obj is a jQuery extended object obtained like obj = $(...) etc. And the appendChild method in your code is a method of bare DOM element.

Related

how can i create an image array, each with a unique id using getElementById in javascript?

Here is the code I have but when I try to use the image reference its value is null. I want to be able to use it to access another image in a table and change the src property to one in the preloadImages array. I have already made the table but I can't get a reference to the individual elements of the preloadImages array. I want each image to have a unique ID using document.getElementById('id') Please help!! Much appreciated!
var preloadImages = new Array();
SIZE = 52;
for(var h=0; h<SIZE; h++){
preloadImages[h] = new Image();
preloadImages[h].src = h+'.png';
preloadImages[h].height =100;
preloadImages[h].width = 70;
preloadImages[h].id = "cardImage"+h+"";
var cardImageRef = document.getElementById("cardImage"+h+"");
document.write(cardImageRef+'h'); //This line is for testing, it just returns null
}
You cannot use getElementById() unless the element exists in the DOM tree. This modification will add them to DOM:
for(var h=0; h<SIZE; h++){
preloadImages[h] = new Image(70, 100); // size here
preloadImages[h].src = h+ ".png";
preloadImages[h].id = "cardImage" + h;
document.body.appendChild(preloadImages[h]); // add to DOM, or some parent element
var cardImageRef = document.getElementById("cardImage" + h);
document.write(cardImageRef + "h"); //This line is for testing, it just returns null
}
However, since you already have the elements referenced in an array you could simply look the element up there using the index for the id (instead of using an id at all). This tend to be faster if your page layout has several elements.
var image = preloadImages[index];
If you where using images not identifiable by index you could do (but probably not relevant in this case):
function getImage(id) {
for(var i = 0; i < preloadImages.length; i++) {
if (preloadImages[i].id === id) return preloadImages[i];
}
return null;
}
So you could use it here, for example:
for(var h=0; h<SIZE; h++){
preloadImages[h] = new Image(70, 100); // size here
preloadImages[h].src = h + ".png";
preloadImages[h].id = "cardImage" + h;
}
document.write(getImage("cardImage0"));
The function document.getElementById() can only be used to reference elements that have already been added to the DOM.
However, if you wish to reference images by their id you can build an object instead and use the id as a key:
var preloadImages = {};
SIZE = 52;
for(var h = 0; h < SIZE; ++h) {
var i = new Image();
i.id = 'cardImage' + h;
i.src = h + '.png';
i.width = 70;
i.height = 100;
preloadImages[i.id] = i;
}
Afterwards you can refer to each image object by its id like so:
var img = preloadImages['cardImage2'];
// do something with image
document.body.appendChild(img); // add to page
There's no reason to use IDs here. In general, it's a "code smell" to construct IDs dynamically and then use getElementById to find them in your document. You can instead just work with the elements themselves.
After the code you posted runs, then preloadImages array contains the added elements. You don't need to use getElementById to find the element you just constructed! And as you found out, you can't use it at all until the element is inserted into the DOM, which you're not ready to do yet!
So in your table logic, you can simply insert the images you created directly using the references you already have in preloadImages:
function makeTable(images) {
var table = document.createElement('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < images.length; i++) {
var td = document.createElement('td');
tr.appendChild(td);
// put the images in the TD
td.appendChild(images[i]);
}
return table; // to be inserted somewhere
}
document.body.appendChild(makeTable(preloadImages));
I think you're getting confused because some people have gotten into the habit of thinking of IDs as the only way of referring to elements. They construct IDs by concatenating strings, then retrieve the element when they need it by using getElementById. In essence, they are using the document itself as a kind of global bag of things from which you retrieve things using ID as a kind of variable name. It's better in such cases to just work with the elements themselves, held in JavaScript variables or arrays.

Remove characters from an element while using appendChild

I'm trying to remove or replace characters in an element while using appendChild as follow:
var options = from.getElementsByTagName("option");
var to = document.getElementById("target");
to.appendChild(options[i].replace("(A)",""));
I tried various different syntax but no luck. Can someone help? Either JQuery or javascript works for me.
Thanks
I assume you're already in a for loop. If so, use the .text property of the option element, and create a new text node.
to.appendChild(document.createTextNode(options[i].text.replace("(A)","")));
Or better, in the loop append to a string, and create a single node at the end.
var txt = "":
for (var i = 0; i < options.length; ++i)
txt += options[i].text.replace("(A)"), "");
}
to.appendChild(document.createTextNode(txt));
If you actually wanted to append a copy of the element itself, then use .cloneNode(true) instead.
for (var i = 0; i < options.length; ++i) {
var clone = to.appendChild(options[i].cloneNode(true));
clone.text = clone.text.replace("(A)", "");
}

get the text of a div

I have been trying to get the text from a div using only javascript.
I started with jQuery using the following code:
var divText = $("div.Xr3").html();
Then for my JavaScript I tried:
var divText = document.getElementsByClassName("Xr3").innerHtml;
Which returns undefined. How can I accomplish this using JavaScript only?
getElementsByClassName returns a live array of HTML elements, so you can't access innerHTML directly like this. You will either have to loop over its results, or if you know there's only one, apply [0] to it before accessing innerHTML.
var divTexts = [];
var divs = document.getElementsByClassName("Xr3");
var numDivs = divs.length;
while (var i = 0; i < numDivs; i++) {
divTexts.push(divs[i].innerHtml);
}
or, in a single-element scenario,
var divText = document.getElementsByClassName("Xr3")[0].innerHtml;
If Xr3 is used one time, you can use
var divText = document.getElementsByClassName("Xr3")[0].innerHtml;

How do I make a deep copy of a dynamically created element in jQuery?

I want to dynamically generate 8 new paragraphs with jQuery:
http://jsfiddle.net/johnhoffman/Dfydn/
However, this snippet of jQuery only adds a single paragraph to my div (with the text "7" in it).
var attached = $("<p>");
var sandbox = $("#sandbox");
for (var i = 0; i < 8; i++) {
// How come reseting attached works? attached = $("<p>");
attached.html(i).appendTo(sandbox);
}​
HTML: <div id="sandbox"></div>​
I do not want to run attached = $("<p>"); for every iteration of the loop because I want to make use of the prototype design pattern - I want to build a paragraph and then alter copies of it to preventing having to build from scratch every time. How do I make a deep copy of a dynamically created element?
You might try this. Use the .clone() method. Also you don't need the .html(i) when you're using clone(). Because clone returns a jQuery object you don't even need to wrap a $() around it.
var attached = $("<p>");
var sandbox = $("#sandbox");
for (var i = 0; i < 8; i++) {
attached.clone().appendTo(sandbox);
}
​Also if you want to clone the event handlers you should use .clone(true). See http://api.jquery.com/clone/ for more info about clone()
The jQuery .clone() method is precisely for making deep copies. From the documentation:
Description: Create a deep copy of the set of matched elements.
Example:
var attached = $("<p>");
var sandbox = $("#sandbox");
for (var i = 0; i < 8; i++) {
$(attached).clone().appendTo(sandbox);
}​
var attached = $("<p>");
var sandbox = $("#sandbox");
for (var i = 0; i < 8; i++) {
// How come reseting attached works? attached = $("<p>");
attached.clone().html(i).appendTo(sandbox);
}​

Extracting specific lines in a chunk of text which contains a specific word, javascript

I am currently have a chunk of string which actually a html source code stored in it. What I am trying to do now is to read out specific tags which I require using javascript. Can anyone help me with this, I am new to programming and I am not too sure how to go about it.
The problematic code:
if (request.readyState == 4) {
var html_text = request.responseText;
var parent = document.createElement('div');
parent.innerHTML = html_code;
var metas = parent.getElementsByTagName('meta');
var meta;
for (var i = 0; i < metas.length; i++) {
meta = metas[i];
alert(meta.property);
alert(meta.content);
}
}
The meta content works, but just that the meta property returned are undefined.
Use the DOM (Document Object Model) API. The Mozilla Dev Network (née Mozilla Dev Center) is a great starting point an all-around reference.
JavaScript Guide
The DOM and JavaScript
Traversing an HTML table with JavaScript and DOM Interfaces
What I am trying to do now is to read out specific tags which I require using javascript.
var text = /* whatever string that contains HTML */;
First you need to parse the string:
var parent = document.createElement('div');
parent.innerHTML = text;
Then you can search for whatever kind of element you're looking for. Say you're looking for <table> elements.
var tables = parent.getElementsByTagName('table');
Now you can do whatever you need to each element found:
var table;
for (var i=0, len=tables.length; i<len; i++)
{
table = tables[i];
// do something with the element
}
Relevant API docs
document.createElement
element.innerHTML
element.getElementsByTagName
Attributes of XML nodes are not readily available as DOM object properties. Use getAttribute
Sample: http://jsfiddle.net/mendesjuan/6Pdmw/
var node = document.createElement('div');
node.innerHTML = "<meta property='prop1' content='cont1'>"+
"<meta property='prop2' content='cont2'>";
var metas = node.getElementsByTagName('meta');
for (var i = 0; i < metas.length; i++) {
var meta = metas[i];
alert(meta.getAttribute("property"));
alert(meta.getAttribute("content"));
}

Categories