Apply javascript just in a div? - javascript

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);

Related

javascript - unable to replace the html page with images

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;})()

Selecting elements without jQuery

I guess this will be voted down, as it doesn't contain enough jQuery, but here it goes :)
What is the most effective way to get the element(s) returned by the jQuery selector below using plain old javascript?
$('a[title="some title text here"]', top.document)
If you're using a modern browser, you could use this:
window.top.document.querySelectorAll('a[title="some title text here"]')
Not sure if it’s the most effective, but at least it works.
var links = top.document.getElementsByTagName('a');
var result = [];
var linkcount = links.length;
for ( var i = 0; i < linkcount; i++) {
if (links[i].getAttribute('title') === 'some title text here') {
result.push(links[i]);
}
}
Here is an example
var getElements = function(tagName, attribute, value, callback) {
var tags = window.document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tag = tags[i];
if (tag.getAttribute(attribute) == value) {
callback(tag);
}
};
};
getElements("a", "title", "PHP power player at Hettema & Bergsten. Click to learn more.", function(tag) {
console.log(tag);
});

how check if link go for certain site using javascript

how check if link go for certain site using javascript
function checkLinks() {
var anchors = document.getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
if (anchor.href == "http://google.com"){/*compare not working*/
alert("exist");
}
}
}
Try using anchor.getAttribute('href').
You could use regexp to try and match the links. With this method, it checks if it is directing to that domain (what exact url doesn't matter, as long as it has "google.com" somewhere in the URL):
function checkLinks() {
var anchors = document.links;
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i].href;
var re = new RegExp("google\.com","ig");
if (re.test(anchor)){
alert("exist");
}
}
}
example: http://jsfiddle.net/niklasvh/ELg6d/
Your compare isn't working because that's not what .href is returning. I'm guessing if you looked at the actual value of href, it would have another '/' on the end.

Listing known CSS classes using Javascript

I'm trying to find a good way to collect the names of classes defined in the stylesheets included with a given document. I know about document.StyleSheetList but it doesn't seem like it'd be easy to parse. What I'm looking for is something like, for a stylesheet document such as:
.my_class {
background: #fff000;
}
.second_class {
color: #000000;
}
I could extract an array like ["my_class", "second_class"]. This obviously assumes the favorable scenario of a fully loaded dom and stylesheets.
I've been looking everywhere for a good way to do something like this and so far, have made little progress. Does anyone have any idea about how to pull this off? Thanks!
This will show all rules defined in the stylesheets.
var allRules = [];
var sSheetList = document.styleSheets;
for (var sSheet = 0; sSheet < sSheetList.length; sSheet++)
{
var ruleList = document.styleSheets[sSheet].cssRules;
for (var rule = 0; rule < ruleList.length; rule ++)
{
allRules.push( ruleList[rule].selectorText );
}
}
The thing, though, is that it includes all rules regardless of being class or tag or id or whatever..
You will need to explain in more detail what you want to happen for non class rules (or combined rules)
You were on track with document.styleSheets (https://developer.mozilla.org/en/DOM/document.styleSheets)
https://developer.mozilla.org/en/DOM/stylesheet.cssRules
Here's a quick and dirty method to output all class selectorTexts to the console in Firefox + Firebug.
var currentSheet = null;
var i = 0;
var j = 0;
var ruleKey = null;
//loop through styleSheet(s)
for(i = 0; i<document.styleSheets.length; i++){
currentSheet = document.styleSheets[i];
///loop through css Rules
for(j = 0; j< currentSheet.cssRules.length; j++){
//log selectorText to the console (what you're looking for)
console.log(currentSheet.cssRules[j].selectorText);
//uncomment to output all of the cssRule contents
/*for(var ruleKey in currentSheet.cssRules[j] ){
console.log(ruleKey +': ' + currentSheet.cssRules[j][ruleKey ]);
}*/
}
}
This is probably not something you really want to be doing except as part of a refactoring process, but here is a function that should do what you want:
function getClasses() {
var classes = {};
// Extract the stylesheets
return Array.prototype.concat.apply([], Array.prototype.slice.call(document.styleSheets)
.map(function (sheet) {
if(null == sheet || null == sheet.cssRules) return;
// Extract the rules
return Array.prototype.concat.apply([], Array.prototype.slice.call(sheet.cssRules)
.map(function(rule) {
// Grab a list of classNames from each selector
return rule.selectorText.match(/\.[\w\-]+/g) || [];
})
);
})
).filter(function(name) {
// Reduce the list of classNames to a unique list
return !classes[name] && (classes[name] = true);
});
}
What about
.something .other_something?
Do you want a pool of classNames that exist? Or a pool of selectors?
Anyway, have you tried iterating through document.styleSheets[i].cssRules? It gives you the selector text. Parsing that with some regexp kungfu should be easier...
Do you need it to be crossbrowser?
You can accompish this with jQuery. Example would be
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var allobjects = $("*")
});
</script>
Check out the jQuery website: http://api.jquery.com/all-selector/

anyway to delete all <a href=> tags with javascript after the page loads on an iPad?

I know that I can run a line of javascript code after the page loads on an iPad with UIWebView (which is what I am using), but I do not know what I could type to go through and remove all of the tags. I also would like to be able to do this to only certain parts of the page e.g. only remove tags within a certain tag.
You can get all elements by tag name using document.getElementsByTagName(). All links have the tag name a. You can visually remove them by setting their display style to none.
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
To remove elements of a certain tag within a certain tag, just invoke getElementsByTagName() on the element in question. Suppose that you want to hide all links inside a <li> only:
var listitems = document.getElementsByTagName('li');
for (var i = 0; i < listitems.length; i++) {
var anchors = listitems[i].getElementsByTagName('a');
for (var j = 0; j < anchors.length; j++) {
anchors[j].style.display = 'none';
}
}
The element.parentNode.removeChild(element) is also a good one, but it doesn't work nicely inside a standard for loop. You need to loop backwards:
var elements = document.getElementsByTagName('a');
for (var i = elements.length; i-- > 0;) {
var element = elements[i];
element.parentNode.removeChild(element);
}
Update as per the clarified functional requirement: you thus want to replace the link element with a text node representing the link's original content? You can use Node.replaceChild() for this. Here's a kickoff example:
var elements = document.getElementsByTagName('a');
for (var i = elements.length; i-- > 0;) {
var element = elements[i];
var text = document.createTextNode(element.firstChild.nodeValue);
element.parentNode.replaceChild(text, element);
}
Thought I'd post a remove() function to complement BalusC:
function remove(el){
if(el.parentNode)el.parentNode.removeChild(el);
}
Note: If the element doesn't have a parent, it means it is not in the DOM tree.
It also means it will be removed in the GC's (garbage collector) next run (as long as there are no references to it).
If you're going to be doing a lot of dom manipulation, it might be worth it to include jQuery to grab your elements. It'd be a little easier to remove items. Eg.
$(function(){
$('.surrounding_class a').remove();
});
If you want to remove links but preserve their display contents (text, images, etc.) you can insert their childNodes before the links, then remove the link elements:
var removeLinks = function(context) {
var undefined;
if(context === undefined) {
context = document;
}
if(!context) {
return false;
}
var links = context.getElementsByTagName('a'), i, link, children, j, parent;
for(i = 0; i < links.length; i++) {
link = links[i];
parent = link.parentNode;
if(!link.href) {
continue;
}
children = link.childNodes;
for(j = 0; j < children.length; j++) {
parent.insertBefore(children[j], link);
}
parent.removeChild(link);
}
return context;
};
// Use:
removeLinks(document.getElementById('container'));

Categories