javascript - unable to replace the html page with images - javascript

I am trying to replace everything with only images for images.google.com with some search term.
I tried the below code with firebug but says undefined.
document.body.innerHTML=document.getElementsByTagName('img').innerHTML
On the page [undefined] appears
I checked only
document.getElementsByTagName('img').innerHTML
It says undefined.
I checked only
document.getElementsByTagName('img')
It shows me lot of img elements
What is wrong.

If you want to reduce the contents of the <body> to a particular collection of elements, you could try:
// `slice` to get an `Array` vs. `NodeList`, which may be "live"
var imgs = Array.prototype.slice.call(document.querySelectorAll('img.rg_i'), 0);
// clear out current contents
document.body.innerHTML = '';
// append each `<img>` back into the `<body>`
for (var i = 0, l = imgs.length; i < l; i++) {
imgs[i].style.display = 'inline';
document.body.appendChild(imgs[i]);
document.body.appendChild(document.createTextNode(' '));
}

Try to do this:
var objs = document.getElementsByTagName('img');
if (objs) {
// there might be more than one
document.body.innerHTML = objs[0].parentNode.innerHTML;
}

Img tags do not have innerHTML and getElementsByTagName is plural.
You can do
var imgs = document.images,html=""; // or document.getElementsByTagName("img");
var div = document.createElement("div");
for (var i=0;i<imgs.length;i++) {
div.appendChild(imgs[i]);
}
document.body.innerHTML=div.innerHTML;
Here is an even more google image specific version based on Jonathan's code
I tested it in the Chrome console on a google image search
(function() {
var links=document.querySelectorAll('a.rg_l'),html=[];
for (var i=0, n=links.length;i<n;i++) {
html.push(links[i].innerHTML);
}
document.body.innerHTML=html.join(" - "); // or whatever you want between images
html=null;})()

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.

Javascript - find all classes from array, grab and return inner text from classes

I have an array of class names that I want to search a page for. Then I'd like to find all those elements, grab the text inside, and append it to a div.
var div = document.createElement('div');
div.innerHTML = 'List of names from this page';
document.body.appendChild(div);
var classNameArray = ['user', 'username', 'fullname', 'profile-field', 'author', 'screen-name'];
for (var i = 0; i < classNameArray.length; i++) {
element = classNameArray[i];
getSuggestedAuthors(element);
function getSuggestedAuthors(element) {
var classes = document.getElementsByClassName(element);
var index;
for (var index = 0; index < classes.length; index++) {
var class = classes[index];
var textInsideClass = class.innerHTML;
div.appendChild(textInsideClass);
}
}
}
When I run this, it gives me:
Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist.
I believe the problem is occuring at var textInsideClass = class.innerHTML, because when I remove that, it simply grabs all the classes and appends them to the div. However, I'd like to only get the text inside the class.
Anyone know how to do this without jQuery? I'm injected this hs through Google Chrome's executeScript injection.
Thanks so much!
I think your issue is that appendChild only works with nodes. You might be better off just appending to innerHTML using something along the lines of a.innerHTML += f.innerHTML.
You should also be sure to move the getSuggestedAuthors function out of the loop. It works ok as it is, but it's much better form not to declare functions inside a loop.
If you only need to support chrome then all of the handy methods on the Array.prototype should exist :)
var a = document.createElement('div');
a.innerHTML = 'List of names from this page';
document.body.appendChild(a);
function getSuggestedAuthors(elements) {
for (var d = 0; d < elements.length; d++) {
a.appendChild(document.createTextNode(elements[d].innerText));//append loop items text to a
}
}
['user', 'username', 'fullname', 'profile-field', 'author', 'screen-name'].map(function(cls) {
return document.getElementsByClassName(cls);
}).forEach(getSuggestedAuthors);

Apply javascript just in a div?

I have coded a few lines which extract the URL of all the img tags in the page.
Ok everything works well but I wonder if there is a way to apply my code in a special div in the page!!!?
I mean I want to get URL of img tags from a div not from the whole page body.
I hope that I explained clearly what I meant :)
Any solution would be appreciated
function getURL() {
var url = [];
var a = document.getElementsByTagName('img');
for (var i=0, j = a.length; i<j; i++)
{
if (/\.(jpg|jpeg|gif|png)$/im.test(a[i].getAttribute('src')))
{
url.push(a[i].getAttribute('src'));
}
}
document.write(url);
}
Replace document.getElementsByTagName('img') with yourElement.getElementsByTagName('img');
Change your function to accept a startElement parameter, then call the getElementsByTagName on the passed element
function getURL(startElement) {
var url = [];
var a = startElement.getElementsByTagName('img');
for (var i=0, i < a.length; i++)
{
if (/\.(jpg|jpeg|gif|png)$/im.test(a[i].getAttribute('src')))
{
url.push(a[i].getAttribute('src'));
}
}
return url; // return the result instead of writing it
}
Say you have this markup
<div id='myDiv'><img src='test.jpg'/></div>
You could then call
var urls = getUrl(document.getElementById('myDiv'));
Also I suggest not using document.write, open dev tools (usually F12) and use console.log instead,
console.log(urls);

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;

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