So I am writing a script that can be run on a page but I want to click on this element, unfortunately, it does not have an id to get and I am trying to use the .click() function on it, but it doesn't work, here's what I have, anyone know how to fix it? This is the only element in the class also
var classes = document.getElementsByClassName('rateRecipe btns-one-small');
var Rate = classes[0];
Rate.click();
I'd suggest:
document.querySelector('.rateRecipe.btns-one-small').click();
The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:
document.querySelector('.rateRecipe .btns-one-small').click();
The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.
References:
document.getElementsByClassName().
document.querySelector().
If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).
var divs = document.querySelectorAll('.love-button.love-button--loved');
for (i = 0; i < divs.length; ++i) {
divs[i].click();
};
With ES6 and Babel (cannot be run in the browser console directly)
[...document.querySelectorAll('.love-button.love-button--loved')]
.forEach(div => { div.click(); })
for exactly what you want (if you know the index of button):
var rate = document.getElementsByClassName('rateRecipe btns-one-small')[0];
rate.click();
or for direct action
document.getElementsByClassName('rateRecipe btns-one-small')[0].click();
with jQuery
$('.rateRecipe .btns-one-small').click(function(){
var vIndex = $('.rateRecipe .btns-one-small').index(this);
//vIndex is the index of buttons out of multiple
//do whatever
//alert($(this).val());//for value
});
class of my button is "input-addon btn btn-default fileinput-exists"
below code helped me
document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();
but I want to click second button, I have two buttons in my screen so I used querySelectorAll
var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
elem[1].click();
here elem[1] is the second button object that I want to click.
Related
I have this link on my web page:
Terms and conditions
I want to use Jquery to check whether this specific link is present or not on the web page. I know how to check if text is present on a page, but am struggling a little with links. If it helps, it is only the terms-conditions-mywebsite bit that I need to use (as mywebsite changes depending on who is using the site).
The class is footer so I have tried $('.footer:contains("terms-conditions") but this doesn't seem to work. Any pointers would be appreciated, thanks so much :)
Edit: I need to check that the actual specific contents of this links is present, rather than the text 'Terms and conditions'
You should check the value of href attribute. You can use Attribute Contains Selector [name*=”value”] which select elements that have the specified attribute with a value containing a given substring:
The following should work:
if($('a[href*=terms-conditions]').length){
//exist
}
OR: Check the link string directly
if($('a:contains("Terms and conditions")').length){
//exist
}
I would look at doing this with Javascript, as it's very straightforward and means you are not reliant on JQuery should you wish to remove JQuery from the site at a later date.
// get <a> elements
var links = document.getElementsByTagName('a');
// loop through each <a>
for (var i = 0; i < links.length; i++) {
// get each href
var hrefs = links[i].getAttribute("href");
// check href against the one you want
if (hrefs == "https://www.google.com") {
// check content of link
console.log('link content:', links[i].innerHTML)
}
}
I am trying to add a second class to my element
Before
<div class="foo1">
<a class="class1" >Text</a>
</div>
After
<div class="foo1">
<a class="class1 class2" >Text</a>
</div>
here is my javascript code (tried but no success):
window.onload = function() {
document.getElementById('class1').className = 'class2';
};
UPDATE
actually, all of your answers work, but since this (class1) is a click event, by running the codes it temporarily adds the second class (class2) to the class1 but when page is reloaded , it has disappeared. I need to implement it via a click event by clicking class1. How do I do it?
2nd UPDATE
actually the site users have the ability to change this class, so I am trying to make this happen: that a user changes a class by clicking on class1 and making it "class1 class2"
Two problems with your code:
You're trying to look up class1 as an id, but you don't have any element with id="class1"; I assume you want to look up elements with that class, but that's not what getElementByid does
You're overwriting the class list by assigning to className; instead, you need to append to it (including a space, so you end up with the right string).
If you want to add the second class to all elements that have class1, you'll need a loop:
[].forEach.call(document.querySelectorAll(".class1"), function(element) {
element.className += " class2";
});
querySelectorAll works on all modern browsers, and also IE8. It accepts a CSS selector and returns a list of matching elements. Then, in the above, I loop over the list by borrowing Array#forEach, which is happy to loop through array-like things like the lists from querySelectorAll.
I should mention that if you want to use forEach on IE8, you'll need a polyfill for it. Or of course, use a boring old loop:
var list = document.querySelectorAll(".class1");
var n;
for (n = 0; n < list.length; ++n) {
list[n].className += " class2";
}
Or if you only want to do it if they're inside a .foo1:
[].forEach.call(document.querySelectorAll(".foo1 .class1"), function(element) {
element.className += " class2";
});
Or only direct children of a .foo1:
[].forEach.call(document.querySelectorAll(".foo1 > .class1"), function(element) {
element.className += " class2";
});
Suggested reading:
MDN
DOM
CSS Selectors
In case you're using jQuery and forgot to tag it (hey, it happens):
All:
$(".class1").addClass("class2");
Only inside a .foo1:
$(".foo1 .class1").addClass("class2");
Or only direct children of a .foo1:
$(".foo1 > .class1").addClass("class2");
To get all the elements with that class:
var elements = document.getElementsByClassName('class1');
Then loop over them:
for (var i = 0; i < elements.length; i++)
You need to concat the values:
element.className += ' class2';
So the full code looks like this:
var elements = document.getElementsByClassName('class1');
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.className += ' class2';
}
Example (.class2 elements have red colour):
var elements = document.getElementsByClassName('class1');
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.className += ' class2';
}
.class2 {
color: red
}
<div class="class1">1</div>
<div class="class1">2</div>
Or, if your browser supports classList (as most modern browsers do), then something like this will work as well:
element.classList.add('class2');
AFTER THE QUESTION UPDATE
but since this is a click event, it temporarily adds the second class but when page is reloaded , it has disappeared. I need to implement it via a click event. How do I do it?
Ideally, you'd use a server-side language to maintain changed classes after a page reloads. Normally, when you reload a page, your whole DOM reloads (including the classes).
There is a client-side solution, but not recommended: use a storage mechanism, like sessionStorage, localStorage, or plain old cookie, to keep track of click events. And then, when you render the page, simply check the storage for those click events you tracked, and adjust classes accordingly using the code above.
Why not recommended? Because this is a way of faking a server-side behaviour using a client-side language. Ideally, if you want to keep things on the client, you'd avoid the page reload completely and have everything happen on a single page (like SPAs do). But I'm afraid I can't tell you much more unless you provide more details about what are you trying to do.
Here's a super-simple example using localStorage, note how it keeps the class settings after a refresh:
http://jsfiddle.net/73efLsht/
For example I have long list of buttons: <input type=button name=clickbutton onclick='dosomething(this)'>
But instead of putting call to the same function in every button it would be more rational to add a single listening event that would wait for click of that button with this name. But again, there are many this buttons so I need pass clicked object to a function. For example this function must update a textarea field that is adjacent (nextSibling) to this button.
You could use jQuery:
$('input[name|="clickbutton"]').click(function() {
var currentButton = $(this);
alert(currentButton.attr('id'));
});
This attaches a click function to all input elements with a name of 'clickbutton'. currentButton is the input element that was just clicked. The function then alerts the id of the currentButton.
UPDATE: I've created a working example for you here: http://jsfiddle.net/Damien_at_SF/cdsWk/1/
Hope that helps :)
Look up event delegation. This may be what you need. There are many good resources for it on google.
Update:
Sorry, I could have put a little more effort into the answer, Here are some results Google Search...
You would then use a switch to determine what action you want to take based on the event.name attribute. Cool thing about that approach is if you have a great deal of elements on the page with events, it sounds like you do, it should make your page feel more responsive; as the browser does not have to deal with the extra overhead of on event per element.
var buttons = document.getElementsByName('clickbutton');
for (var i = 0; i < buttons.length; i++)
buttons[i].onclick = function(){
this.nextSibling.innerHTML = 'clicked!';
}
I'm struggling to decipher a way to remove several specific href elements which contain no IDs and are children of individual parents with no IDs.
The best I can manage is identifying the four offending, out of 8 or 9 href tags (and the number may vary), by a specific word within the URL itself. For this, I do the following:
<script language=javascript>
var xx = document.getElementById('theID').getElementsByTagName('a');
var ptn=/\=media/;
for(var i=0; i<xx.length; i++) {
if(ptn.exec(xx[i])){
alert(xx[i]);
}
}
</script>
Of course all this gives me is the four specific URLs within the href where "=media" is present. Now, somehow, I need to be able to remove either these href elements, or their parent elements (which happen to be unordered list tags). It's not until I get a level higher (table cell) that I gain access to an element ID, or anything distinguishing besides a particular word within the URL itself.
I'm open to any approach at this point - PHP may be an option (I really haven't explored this yet), but for this, javascript was my first logical choice. I can't tamper with the page that generates the links directly, only a secondary page which gets included at page load time.
Any pointers on how to solve this??
======================== final solution =====================
<script language=javascript>
var xx = document.getElementById('theID').getElementsByTagName('a');
var ptn=/\=media/;
for(var i=0; i<xx.length; i++) {
while(ptn.exec(xx[i].href)){
alert(xx[i]);
xx[i].parentNode.removeChild(xx[i]);
}
}
</script>
You don't need the ID to remove an element. You only need a reference to the element (which you seem to have).
instead of this:
alert(xx[i]);
try this:
XX[i].parentElement.removeChild(xx[i]);
You can call removeChild() on the parent element, like so:
xx[i].parentNode.removeChild(xx[i]);
As a side note, your regular expression isn't being executed on the href property. Change your if statement to:
if(ptn.exec(xx[i].href)){
var parent = xx[i].parentNode;
parent.removeChild(xx[i]);
http://www.onlinetools.org/articles/unobtrusivejavascript/chapter2.html has some nice examples of similar operations (scroll down).
Is it possible to apply / create a YUI Button by using an element's class name and not by id. I have to generate a list of buttons then transform it to a YUI button.
[Update]
By the way, I'm trying to apply the button in an anchor tag. So it will be a link button.
[Update:Code]
Ok so here's the code. I have a loop that generates this anchor tag.
<a class="system-button" href="/system/edit/12">Edit</a>
wrumsby's answer perfectly makes sense. But I don't know why it doesn't work. I tried debugging it and the elements are successfully fetched. But it seems that no YUI Buttons are created.
I even tried generating unique ids for the elements but still no luck.
Any ideas?
Looks like I've solved it myself. But I'm not sure if this is the best solution. I generated unique ids then create the buttons.
var i = 0;
$(".system-button").each(function(i,b){
var button = new YAHOO.widget.Button($(b).attr('id','system-button'+i).attr('id'));
i++;
});
And oh yes, I use JQuery here. That framework is so awesome.
You should be able to use the srcelement configuration attribute like so:
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event,
Button = YAHOO.widget.Button;
Event.onDOMReady(
function() {
var elements = Dom.getElementsByClassName('...');
for (var i = 0; i < elements.length; i++) {
var button = new Button({
srcelement: elements[i],
...
});
...
}
}
);
})();