Selecting elements without jQuery - javascript

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

Related

Trying to remove links from variable

$.get("http://en.wikipedia.org/wiki/Afghanistan", function(response) {
var elements = $.parseHTML(response);
var wiki = $(elements).find('#mw-content-text').find("p");
var ps = [];
var arrayLength = wiki.length;
for (var i = 0; i < arrayLength; i++) {
if (wiki[i].innerHTML === "") {
break;
}
var item = wiki[i]
ps.push(item);
$("#fakediv").append(ps);
}
I am trying to remove the links from the variable item, but I can't seem to find any examples of how to do this from a variable - everything assumes that I'll be using a selector.
I've tried .removeAttr("href"), but that doesn't seem to work and I'm not quite sure how to remove links and leave the text.
You say you want to unlink the links, but you are looping over paragraph elements and trying to remove its attribute. I doubt the paragraph has an href attribute.
So you need to find the anchors inside the paragraph tags
var item = wiki.eq(i);
item.find("a").removeAttr("href")
ps.push(item);
or
var item = wiki.eq(i);
item.find("a").contents().unwrap();
ps.push(item);

Replace n patterns in a string

Is there an easy way to fix this code:
title_1 = $(this).closest('tr').find('td').html();
title_2 = $(this).closest('tr').find('td').next().html();
title_3 = $(this).closest('tr').find('td').next().next().html();
question = question.replace(/{title_1}/g, title_1);
question = question.replace(/{title_2}/g, title_2);
question = question.replace(/{title_3}/g, title_3);
So it isn't so dully (repeated) and can cover n occurences of title_ pattern?
I'm a beginner Javascript developer and a complete regular expressions newbie (actually, they scare me! :|), so I'm unable to do this by myself. I've tried to look for an inspiration in different languages, but failed.
You can use a function in the replace, to get the value depending on what you find:
question = question.replace(/{title_(\d+)}/g, $.proxy(function(x, m){
return $(this).closest('tr').find('td:eq('+(m-1)+')').html();
}, this));
Demo: http://jsfiddle.net/n3qrL/
String.prototype.replace() could take a function as second parameter.
var $this = $(this);
question = question.replace(/\{title_(\d+)\}/g, function(match, n) {
return $this.closest('tr').find('td').eq(n - 1).html();
});
Demo Here
Try this ,
Generalized for getting all td tag's text value :
$("table").find("tr").each(function(){
$(this).find("td").each(function(){
alert($(this).html());
var txt=$(this).html();
//var pattern="/{"+txt+"}/g";
//question = question.replace(pattern, txt);
});
});
NB. In your question you have not mentioned the value for 'question' . please define value for 'question'
It seems to me that you want to get the text content of the first three cells of a table row and use it to replace the content of a string, and that this is an element somewhere in the row. So you can do:
var n = 3; // number of cells to get the text of
var textArray = [];
var tr = $(this).closest('tr')[0];
var reString;
for (var i=0; i<n; i++) {
reString = '{title_' + (i+1) + '}';
question = question.replace(reString, tr.cells[i].textContent);
}
If you wish to avoid jQuery's closest, you can use a simple function like:
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
do {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
} while (el.parentNode)
}
then:
var tr = upTo(this, 'tr');

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

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/

removing all option of dropdown box in javascript

How can i dynamically remove all options of a drop down box in javascript?
document.getElementById('id').options.length = 0;
or
document.getElementById('id').innerHTML = "";
var select = document.getElementById('yourSelectBox');
while (select.firstChild) {
select.removeChild(select.firstChild);
}
Setting the length to 0 is probably the best way, but you can also do this:
var mySelect = document.getElementById("select");
var len = mySelect.length;
for (var i = 0; i < len; i++) {
mySelect.remove(0);
}
<select id="thing"><option>fdsjl</option></select>
<script>
var el = document.getElementById('thing');
el.innerHTML = '';
// or this
while ( el.firstChild ) {
el.removeChild( el.firstChild )
}
</script>
Its very easy using JavaScript and DOM:
while (selectBox.firstChild)
selectBox.removeChild(selectBox.firstChild);
The fastest solution I was able to find is the following code (taken from this article):
// Fast javascript function to clear all the options in an HTML select element
// Provide the id of the select element
// References to the old <select> object will become invalidated!
// This function returns a reference to the new select object.
function ClearOptionsFast(id)
{
var selectObj = document.getElementById(id);
var selectParentNode = selectObj.parentNode;
var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
selectParentNode.replaceChild(newSelectObj, selectObj);
return newSelectObj;
}
There is simple and elegant way to do this:
for(var o of document.querySelectorAll('#id > option')) {
o.remove()
}

Categories