Last year I asked a question similar to the question I am asking here-
Create a Bookmarklet that clicks multiple buttons on one page
The accepted answer works perfectly on a page that uses jQuery. However I need to get something similar working on a page that doesn't load jQuery. I tried to insert jQuery into the page in the bookmarklet but it refuses to load (the website doesn't allow it).
How do I convert the following to pure Javascript so that I can click multiple buttons on the page?
(function(){
var UserFollowButton = $('button.UserFollowButton');
var index = UserFollowButton.length-1;
follow();
function follow(){
if(index >= 0){
$(UserFollowButton[index--]).click();
setTimeout(follow, 500);
}
}
})();
To get a list of UserFollowButton equivalent to the query you just ran, you should use getElementsByClassName("UserFollowButton") which gives you an HTMLCollection of elements with a particular class name. Then, you can filter that collection to elements with the tagName equal to BUTTON.
Then, to click it, simply apply the method DOMElement.click to each element in the array. You can do that using forEach.
Array.prototype.slice.call( // convert HTMLCollection to Array
document.getElementsByClassName("UserFollowButton")
).filter(function(element) {
return element.tagName === "BUTTON";
}).forEach(function(element){
element.click();
});
If you want the timeout, then you can simply set UserFollowButton to Array.prototype.slice.call(document.getElementsByClassName("UserFollowButton")).filter(function(element) { return element.tagName === "BUTTON"; });, then do what you are currently doing, using UserFollowButton[i].click() instead of implicit jQuery conversions.
Instead of having a global variable you are indexing from, though, try keeping the array local, passing it as an argument, using pop to take the first element, and keep passing it to subsequent callbacks.
Related
A function in my WP plugin has just randomly (as far as I can tell) stopped working.
Here's the code in question:
window.send_to_editor = function(html) {
var classes = jQuery('img',html).attr('class');
var items = classes.split(" ");
... more stuff here
}
I've confirmed that the html variable is indeed an img html tag. Here's what firebug shows when I do a console.log of the object (console.log(jQuery('img',html));):
Object[]
context -> undefined
jquery -> "1.11.2"
length -> 0
prevObject -> Object[img.alignnone.size-full.wp-image-1234 name.jpg]
And the error it shows is classes is undefined.
I figure there's something wrong with the object I get, but this used to work recently and I'm not aware of any changes in the site that could have caused this.
I'd appreciate any input on this.
EDIT:
More info. This happens with two plugins which are supposed to be unrelated (made by different people). It happens when, after uploading an image to the server (or selecting a previously uploaded picture) you try to insert it into the post.
As I said before this error has appeared out of nowhere, it was working as intended a couple days ago. The only thing I can think of that has changed since then is the domain name, but I can't see how that could be related.
The jQuery selector always returns a jQuery object, but when the length is 0 then no elements were found matching the selector that you provided. In your example you've confirmed that nothing is selected as the length of the jQuery object is 0. Perform a check whether an element was selected like this:
var $els = jQuery('img',html),
classes;
if ($els.length) {
classes = $els.attr("class");
}
Keep in mind that your DOM query is limited by what you pass in as the html parameter. If you simply want to find the images on the page do: var $els = jQuery('img');
I finally managed to fix this; the key was parsing the html string variable into proper HTML, using jQuery.parseHTML(). Thanks to everyone who helped!
I have a simple form so user send his vote.
There I need to know what radio button user select.
The version I found to solve it was this. How can I get which radio is selected via jQuery?
value = $('input[name=vote]:checked', '#frmSurvey').val();
This work ok. Even when I dont understand how that work, because in Jquery selector documentation there is only 2 example with item separated by coma. And neither match my example where each element is inside a quote and then a coma
.class , .class ---> $(".intro,.demo") All elements with the class "intro" or "demo"
el1 , el2 , el3 ---> $("h1,div,p") All < h1>, < div> and < p> elements
Both looks like OR selector instead of find A and then find B inside A.
So if anyone can tell me what kind of selector is that I would love to take a look into the documentation
Now the optimization I was thinking. If I already inside a function for #frmSurvey won't be faster if I use the this element
$('#frmSurvey').ajaxForm(function () {
value = $('input[name=vote]:checked', '#frmSurvey').val();
console.log('working way ' + value);
value = $(this).find('input[name=vote]:checked').val();
console.log('testing way ' + value);
But I couldn't make the second version to work. Second value get me undefined.
So how I fix second version?
And would be second version better than first one as my instinct suggest or I'm worrying too much?
Your first example shows a selector operating from a context selector, whereas the documentation you've shown shows a "multiple selectors" selector.
You seem to have partially grasped this as
value = $('input[name=vote]:checked', '#frmSurvey').val();
is essentially the same as
value = $('#frmSurvey').find('input[name=vote]:checked').val();
However, the context of "this" inside your function is not clear as it depends upon how the ajaxForm plugin is coded. It isn't necessarily the result of your initial selector. After a short play with the plugin, it would appear that this in the context of ajaxForm is the jQuery ajax request object.
I would like to count the number of, let's say, div elements with 'nice' class. I've got the selector div.nice, but don't know which casperjs class/method to use.
There is a tester.assertElementCount method in fact, but is there anything that simply returns the number of elements?
Just
document.querySelectorAll("div.nice").length
If you can use jquery its fairly simple:
var count = $('div.classname').length;
Found an SO Post that seems to explain using jquery with casperjs, I have no experience with casperjs so I can't help much there.
One of the examples for CasperJS 1.1-beta3 involves checking the number of Google search results for CasperJS. It references __utils__.findAll(), which takes a selector as its argument. It allows you to check the number of items returned using the length property available to any JS object:
test.assertEval(function() {
return __utils__.findAll("h3.r").length >= 10;
}, "google search for \"casperjs\" retrieves 10 or more results");
I've never tried it, but it seems like this utility function can be used outside a conditional, and it will allow you to report the number of elements without using jQuery, as a previous answer recommended.
Casper provides getElementsInfo, you can use the attribute length to get the number of elements.
e.g.
casper.getElementsInfo('myElement').length
you also can use assertElementCount to assert the count of the elment
test.assertElementCount("div.nice", 1)
I did not find the answers above to be helpful to my cause.
I think the goal was to count the number of elements without having to evaluate the js code in the page context, which could be frustrating overtime and have conflicting variables and functions.
Instead, it would be nice to leverage the casper automation context. This can be done with a combination of ".exists()" and the css psuedo-selector ":nth-of-type(i)"
The code below does this...
var counter = 1; //set to one, for css selector setup
casper.then(function() { //wait your turn
//loop through our element
while(casper.exists( 'div span:nth-of-type(' + counter + ')' )) {
counter++; //count the results
}
});
You could make this a function and pass in all the arguments, or just copy and paste it as a step.
Best part, you could follow it with a repeat statement for a pretty cool loop.
casper.then(function(){
this.repeat(counter, function() {
console.log("Another one - item #" + counter);
});
});
So, I have some code that should do four things:
remove the ".mp4" extension from every title
change my video category
put the same description in all of the videos
put the same keywords in all of the videos
Note: All of this would be done on the YouTube upload page. I'm using Greasemonkey in Mozilla Firefox.
I wrote this, but my question is: how do I change the HTML title in the actual HTML page to the new title (which is a Javascript variable)?
This is my code:
function remove_mp4()
{
var title = document.getElementsByName("title").value;
var new_title = title.replace(title.match(".mp4"), "");
}
function add_description()
{
var description = document.getElementsByName("description").value;
var new_description = "Subscribe."
}
function add_keywords()
{
var keywords = document.getElementsByName("keywords").value;
var new_keywords = prompt("Enter keywords.", "");
}
function change_category()
{
var category = document.getElementsByName("category").value;
var new_category = "<option value="27">Education</option>"
}
remove_mp4();
add_description();
add_keywords();
change_category();
Note: If you see any mistakes in the JavaScript code, please let me know.
Note 2: If you wonder why I stored the current HTML values in variables, that's because I think I will have to use them in order to replace HTML values (I may be wrong).
A lot of things have been covered already, but still i would like to remind you that if you are looking for cross browser compatibility innerHTML won't be enough, as you may need innerText too or textContent to tackle some old versions of IE or even using some other way to modify the content of an element.
As a side note innerHTML is considered from a great majority of people as deprecated though some others still use it. (i'm not here to debate about is it good or not to use it but this is just a little remark for you to checkabout)
Regarding remarks, i would suggest minimizing the number of functions you create by creating some more generic versions for editing or adding purposes, eg you could do the following :
/*
* #param $affectedElements the collection of elements to be changed
* #param $attribute here means the attribute to be added to each of those elements
* #param $attributeValue the value of that attribute
*/
function add($affectedElements, $attribute, $attributeValue){
for(int i=0; i<$affectedElements.length; i++){
($affectedElements[i]).setAttribute($attribute, $attributeValue);
}
}
If you use a global function to do the work for you, not only your coce is gonna be easier to maintain but also you'll avoid fetching for elements in the DOM many many times, which will considerably make your script run faster. For example, in your previous code you fetch the DOM for a set of specific elements before you can add a value to them, in other words everytime your function is executed you'll have to go through the whole DOM to retrieve your elements, while if you just fetch your elements once then store in a var and just pass them to a function that's focusing on adding or changing only, you're clearly avoiding some repetitive tasks to be done.
Concerning the last function i think code is still incomplete, but i would suggest you use the built in methods for manipulating HTMLOption stuff, if i remember well, using plain JavaScript you'll find yourself typing this :
var category = document.getElem.... . options[put-index-here];
//JavaScript also lets you create <option> elements with the Option() constructor
Anyway, my point is that you would better use JavaScript's available methods to do the work instead of relying on innerHTML fpr anything you may need, i know innerHTML is the simplest and fastest way to get your work done, but if i can say it's like if you built a whole HTML page using and tags only instead of using various semantic tags that would help make everything clearer.
As a last point for future use, if you're interested by jQuery, this will give you a different way to manipulate your DOM through CSS selectors in a much more advanced way than plain JavaScript can do.
you can check out this link too :
replacement for innerHTML
I assume that your question is only about the title changing, and not about the rest; also, I assume you mean changing all elements in the document that have "title" as name attribute, and not the document title.
In that case, you could indeed use document.getElementsByName("title").
To handle the name="title" elements, you could do:
titleElems=document.getElementsByName("title");
for(i=0;i<titleElems.length;i++){
titleInner=titleElems[i].innerHTML;
titleElems[i].innerHTML=titleInner.replace(titleInner.match(".mp4"), "");
}
For the name="description" element, use this: (assuming there's only one name="description" element on the page, or you want the first one)
document.getElementsByName("description")[0].value="Subscribe.";
I wasn't really sure about the keywords (I haven't got a YouTube page in front of me right now), so this assumes it's a text field/area just like the description:
document.getElementsByName("keywords")[0].value=prompt("Please enter keywords:","");
Again, based on your question which just sets the .value of the category thingy:
document.getElementsByName("description")[0].value="<option value='27'>Education</option>";
At the last one, though, note that I changed the "27" into '27': you can't put double quotes inside a double-quoted string assuming they're handled just like any other character :)
Did this help a little more? :)
Sry, but your question is not quite clear. What exactly is your HTML title that you are referring to?
If it's an element that you wish to modify, use this :
element.setAttribute('title', 'new-title-here');
If you want to modify the window title (shown in the browser tab), you can do the following :
document.title = "the new title";
You've reading elements from .value property, so you should write back it too:
document.getElementsByName("title").value = new_title
If you are refering to changing text content in an element called title try using innerHTML
var title = document.getElementsByName("title").value;
document.getElementsByName("title").innerHTML = title.replace(title.match(".mp4"), "");
source: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
The <title> element is an invisible one, it is only displayed indirectly - in the window or tab title. This means that you want to change whatever is displayed in the window/tab title and not the HTML code itself. You can do this by changing the document.title property:
function remove_mp4()
{
document.title = document.title.replace(title.match(".mp4"), "");
}
I'm trying to re-write the URLs of a set of links that I select using a jQuery class selector. However, I only wish to re-write the links that don't already have a href attribute specified, so I put in an if/else construct to check for this... However, it's not working. It does work without the if else statement so I'm pretty sure that is where I screwed up. I'm new to both JavaScript and jQuery so sorry if my question is elementary and/or overly obvious.
var url = window.location;
var barTwitter = $("a.shareTwitter").attr('href');
if (barTwitter).val() == "null") {
$("a.barTwitter").attr('href','http://www.twitter.com/home?status='+ url +'');
} else {
$("a.barTwitter").attr('href',barTwitter);
}
if (barTwitter).val() == "null") {
This is syntactically invalid (count the parentheses!). You rather want to do:
if (barTwitter.val() == "null") {
Further, the val() function only works on input elements which are wrapped by jQuery, not on element attribute values which are at end just normal variables. You rather want to compare normal variables against the literal null:
if (barTwitter == null) {
There are actually a few problems with your code... BalusC correctly describes the first one - syntax errors in your if condition - but you should probably consider some of the rest...
I'll start with your code corrected according to BalusC's answer, with comments added to describe what's happening:
var url = window.location; // obtain the URL of the current document
// select the href attribute of the first <a> element with a shareTwitter class
var barTwitter = $("a.shareTwitter").attr('href');
if (barTwitter == null) { // if that attribute was not specified,
// set the attribute of every matching element to a combination of a fixed URL
// and the window location
$("a.barTwitter").attr('href','http://www.twitter.com/home?status='+ url +'');
} else {
// set the attribute of every matching element to that of the first
// matching element
$("a.barTwitter").attr('href',barTwitter);
}
Other issues with your code
Ok... now the problems:
jQuery matches sets - a single selector can potentially match multiple elements. So if there are multiple links on the page with the shareTwitter class, you'll be pulling the href attribute for the first one, but changing all of them. That's probably not what you want, although if there is only a single link with that class then you don't care.
In the else clause, you're not actually modifying the href at all... Unless you have multiple matching links, in which case you'll change all of them such that they have the href of the first one. Again, probably not what you want, although irrelevant if there is only one link... So, in the best-case scenario, the else clause is pointless and could be omitted.
You can actually omit the if/else construct entirely: jQuery allows you to test for the existence of attributes in the selector itself!
You're including the URL of the current page in the querystring of your new, custom URL - however, you're not properly escaping that URL... This could cause problems, as full URLs generally contain characters that are not strictly valid as part of URL querystrings.
Notes on working with JavaScript
A quick aside: if you plan on doing any development using JavaScript, you should obtain some tools. At minimum, install Firebug and familiarize yourself with the use of that and JSLint. The former will inform you of errors when the browser fails to parse or execute your code (in addition to many, many other useful debugging and development tasks), and the latter will check your code for syntax and common style errors: in this case, both tools would have quickly informed you of the initial problems with your code. Instructing you in the proper use of these tools is beyond the scope of this answer, but trust me - you owe it to yourself to take at least a few hours to read up on and play with them.
Toward safer code
Ok, back to the task at hand... Here's how I would re-write your code:
var url = window.location; // obtain the URL of the current document
// escape URL for use in a querystring
url = encodeURIComponent(url);
// select all <a> elements with a shareTwitter class and no href attribute
var twitterLinks = $("a.shareTwitter:not([href])");
// update each selected link with a new, custom link
twitterLinks.attr('href', 'http://www.twitter.com/home?status='+ url +'');
Note that even though this new code accomplishes the same task, it does so while avoiding several potential problems and remaining concise. This is the beauty of jQuery...
firs of all your syntax is screwed up: if (barTwitter).val() == "null") should be if (barTwitter.val() == "null") or if ((barTwitter).val() == "null")
Secondly barTwitter is either going to be a string or null so you cant call val which is a jQuery Object method specific to input elements.
Lastly you probably dont want to compare to null because it possible the value will be an empty string. Thus its better to use length property or some other method. A sample with lenght is below.. but im not sure what attr returns if if ther eis no value... check the docs.
var url = window.location;
var barTwitter = $("a.shareTwitter").attr('href');
if (barTwitter.length < 1) {
$("a.barTwitter").attr('href','http://www.twitter.com/home?status='+ url +'');
} else {
$("a.barTwitter").attr('href',barTwitter);
}