I have got something like this in html
<div class="change"><div>
<div class="change"><div>
<div class="change"><div>
<div class="change"><div>
Now here we go for the java script
var base = document.getElementsByClassName("change");
base[0].setAttribute();
console.log(base[0]);
From the console I can see that I"m getting an object but I can't edit it this way, is there any other possibility to edit/add attributes( i need to add a onclick function to like 100 elements).
It's pretty difficult to get the higer object by document.getElementById,
so... anyone got a solution for this?^^
You can add attributes like this
var element = document.getElementByClassName('change')[0];
element.setAttribute(attributeName,attributeValue);
Just use jQuery. Then it's just a matter of doing something like the following:
$(document).ready(function () {
$('.change').click(function () {
$(this).attr('class', 'new-value');
});
});
JSFiddle demo here.
You can accomplish this using the code below:
var nodes = document.querySelectorAll('.change'),
length = nodes.length,
counter = 0;
for (; counter < length; counter += 1) {
// set an attribute.
nodes[counter].setAttribute('data-test', 'test' + counter);
// add a click event.
nodes[counter].addEventListener('click', function () {
alert('Yep, you clicked me');
}, false);
}
Demo here
Using jQuery:
$('.change').on('click', function() {
// Action
});
Syntax of setAttributte:
Object.setAttributte(attribute, value);
Related
I've viewed a couple of the posts in here regarding this topic but not quite working for my situation. I'm using Tampermonkey userscript manager. I want to hide a bunch of div's after the page is fully loaded. I've tested the code below on the console of the page and it works.
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
This alert also works with the Tampermonkey userscript manager.
window.addEventListener("load", function(){
// code goes below
alert("hello world");
});
However, the following code is not working. Neither the div or the alert is working in this situation.
window.addEventListener("load", function(){
// ....
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
alert("it's working");
});
By the way, I'm a newbie to Javascript so any help is much appreciated.
You currently only hide the first ([0]) div. You need to iterate over all elements to hide them.
I'd suggest using document.querySelectorAll because it's easily iterable:
window.addEventListener("load", function(){
document.querySelectorAll('promotions-personalized-offers-ui-single-offer')
.forEach(e => (e.style.display = 'none'));
});
If you must stick to getElementsByClassName, a spread should do the trick:
window.addEventListener("load", function(){
[...document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')]
.forEach(e => (e.style.display = 'none'));
});
Try this:
var x = 3 //number of div elements to remove
window.onload = function() {
for (var i = 0; i < x; i++) {
var elementid = "div" + i.toString(); //ends up as "div1" or "div3"
var div = document.getElementById(elementid)
document.body.remove(div);
}
The divs would need to look like this:
<div id="div1">Content</div>
<div id="div2">Content</div>
<div id="div3">Content</div>
Alternatively, if you're putting the JavaScript code inside a function that's called after the page loads fully, you can just use this:
var x = 3 //number of div elements to remove
function removeDivs() {
for (var i = 0; i < x; i++) {
var elementid = "div" + i.toString(); //ends up as "div1" or "div3"
var div = document.getElementById(elementid)
document.body.remove(div);
}
Then call the function by using removeDivs().
Tampermonkey by default runs when the DOMContentLoaded event is dispatched. https://www.tampermonkey.net/documentation.php#_run_at Based on what you have posted it does not look like you need the event listener at all. Your script would only need one line.
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
How to 1) get and 2) output the current value of my odometer on button click? The snipet which should do that is at the bottom of the JavaScript but it does not work.
My code: https://jsfiddle.net/aht87opr/8/
Documentation of odometer might come in handy:
http://brock-family.org/gavin/software/web/odometer.html (where it says "Get the current value from the odometer: val = myOdometer->get();")
//My attempt to output the current value from the odometer:
$('button').click(function() {
n = myOdometer.get();
return n;
});
You should just use myOdometer.get(), which already gives you the number you are looking for.
If you want to put the value inside the #value element you can use the following:
$('button').click(function() {
var mefedron = myOdometer.get();
$('#value').text(mefedron);
});
Here is the fix in your jsfiddle:
https://jsfiddle.net/aht87opr/14/
Here's a working fiddle - https://jsfiddle.net/6abu3ruf/ (you'll have to fix the CSS)
There are two issues with the fiddle you shared:
You don't have to do mefedron.val();, mefedron has the value you are looking for.
You are not setting that value anywhere.
So basically, just change your onclick to:
$('button').click(function() {
var mefedron = myOdometer.get(n);
$("#value").text(mefedron);
});
I tried your code and confirm(Math.floor(mefedron*10)); works.
$('button').click(function() {
var mefedron = myOdometer.get(n);
confirm(Math.floor(mefedron*10)); // it works
function number() {
return mefedron.val();
}
number();
});
So, if you just want to return the odometer, then on the button click event just return Math.floor(mefedron*10);
To display it on div#value, $("div#value").html(Math.floor(mefedron*10));
just update your button event handler with the following:
$('button').click(function() {
var mefedron = myOdometer.get(n);
mefedron= Math.round(mefedron * 100) / 100
$("#value").text(mefedron)
});
Here is a working version of the code hosted on jsFiddle jsFiddle
I looked at the other solutions on SO for this problem and none of them seem to help my case. To give you some background, yesterday I was trying to select all DIVs by a class and store their IDs. See this Now that I have the IDs I want to create some new elements and incorporate the IDs and be able to click on these new elements. I went to JSFiddle to show you a demo but the crazy part is over there, my code works, yet in my app (Chrome extension) it doesn't. What's even crazier is that I'm already implementing jQuery click events in other parts of it without a problem so I'm really confused why it's not working in this particular case. Here's the JSFiddle that works but in my app it doesn't do anything on click. Thanks for any help! I'm sorry for posting so many (silly) questions.
HTML:
<div class="HA" id="k2348382383838382133"></div>
<div class="HA" id="k2344444444444444444"></div>
<div class="HA" id="k234543544545454454"></div>
<div class="HA" id="k2346787878778787878"></div>
JS:
var HAContainer = document.querySelectorAll('.HA');
var HALength = document.querySelectorAll('.HA').length;
var id = [];
var j = 0;
$('.HA').each(function(){
id[j++] = $(this).attr('id');
});
for (var i=0; i<HALength; i++) {
var HABtn, HABtnImg, HAImgContainer;
HABtnImg = document.createElement("img");
HABtnImg.src = ("http://www.freesmileys.org/smileys/smiley-laughing002.gif");
HABtnImg.className = "ha-icon";
HAImgContainer = document.createElement("div");
HAImgContainer.setAttribute("id", 'HA-'+id[i] + '-container');
HAImgContainer.appendChild(HABtnImg);
HABtn = document.createElement("div");
HABtn.className = 'ha-button';
HABtn.setAttribute("id", 'HA-container');
HABtn.appendChild(HAImgContainer);
HAContainer[i].appendChild(HABtn);
HAClick(id[i]);
}
function HAClick(id) {
$('#HA-'+id+'-container').click(function() {
alert("clicked on ID " + id);
});
}
You have to delegate your event in order to make it work with dinamically added elements:
$('body').on("click", '#HA-'+id+'-container', function() {
alert("clicked on ID " + id);
});
I've noticed something and will edit with a better approach:
Change:
HABtn.setAttribute("id", 'HA-container');
To:
HABtn.setAttribute("id", 'HA-'+id[i] + '-inner-container');
HABtn.setAttribute("class", 'HA-container');
And instead of:
function HAClick(id) {
$('#HA-'+id+'-container').click(function() {
alert("clicked on ID " + id);
});
}
simply attach once the event with delegation:
$('body').on("click", '.HA-container', function() {
alert("clicked on ID " + $(this).attr('id'));
});
jsFiddle implicitly selects the javascript you use to be placed inside of an onload event handler.
As a result your code is wrapped with the onload event handler and basically looks likes this
window.onload = function(){
//your code here
};
The reason it works in jsFiddle is because the script is executing once the DOM is loaded and thus can interact with the elements as they are in the DOM. It is possible that your chrome extension is not acting after the elements have been loaded.
It would be prudent to wrap your javascript in the document.ready shortcut
$(function(){
//your code here
});
Given that, there are still some issues which exist in your code. It is not clear why you need to have that nested div structure, perhaps as a result of css styling, but one issue is the duplication of ids. They could probably just be class names (I am referencing "HA-container").
jQuery offers a very easy way to create elements in the constructor that you can take advantage of here. It will allow your code to be more streamlined and readable.
Further, you can store the id you use inside of the container element's jquery object reference for data using .data('id',value). This will all you to also assign the click event handler immediately inside of using another function to assign it.
jsFiddle Demo
$('.HA').each(function(){
var btn = $('<div class="ha-button HA-container">');
var cont = $('<div id="'+this.id+'-container">').data('id',this.id);
cont.click(function(){ alert("clicked on ID " + $(this).data('id')); });
var img = $('<img src="http://www.freesmileys.org/smileys/smiley-laughing002.gif" class="ha-icon" />');
$(this).append(btn.append(cont.append(img)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="HA" id="k2348382383838382133"></div>
<div class="HA" id="k2344444444444444444"></div>
<div class="HA" id="k234543544545454454"></div>
<div class="HA" id="k2346787878778787878"></div>
I'd re-write it a bit to take advantage of jQuery:
for (var i=0; i<HALength; i++) {
var HABtnImg = $('<img/>')
.attr('src', 'http://www.freesmileys.org/smileys/smiley-laughing002.gif')
.addClass('ha-icon');
var HAImgContainer = $('<div/>')
.attr('id', 'HA-'+id[i] + '-container')
.append(HABtnImg);
var HABtn = $('<div/>')
.addClass('ha-button')
.append(HAImgContainer);
//don't use duplicate ID's here
$(HAContainer[i]).append(HABtn);
}
And later attach the event like so:
$(document).on('click', '.ha-button', function(e){
//your click code here
var id = $(this).find('div').attr('id');
alert("clicked on ID " + id);
});
The idea of this script is to allow dynamically created elements to respond to a keyup function that changes the inner html (or jQuery text()) based on what is inside of a text form.
Each dynamically created element has it's own text form and title. So whatever you type in that given element's text form should become the title for that element which is wrapped in tags.
I've tried a few ways but I just cant get it to work. What is the best way to go about this?
Here's my latest attempt - http://jsfiddle.net/gnkxxgjz/1/
$('body').on('keyup', '.qForms', function() {
var nameOfLoan = [];
var loanOfName = function(t) {
if ($(this).hasClass('.loanNameV'+t)) {
$('body').on('keyup', '.qForms', function() {
var loanN = $('.loanNameV'+t).val();
$('.nameLoan'+t).text(loanN);
});
}
else {
return false;
}
};
for (var t=1; t < z; t++) {
nameOfLoan[t] = loanOfName(t);
}
for (var j=1; j < z; j++) {
nameOfLoan[j]();
}
});
Take a look at this Fiddle
<button onclick="crea()">create</button>
<div id="d1">
</div>
function crea(){
$('#d1').append( $("<h2></h2><input>").on('keyup',function(){
$(this).prev().html( $(this).val() );
}) )
}
Something along these lines:
$(document).on("keypress", $("input"), function(e){
console.log($(e.target).attr("id"))
});
This will print to the console the id attribute of any input field you type into. Please provide how the input and text elements are related and I might be able to link them in this code piece.
I'm using an external script on my website with a form.
Some of the css is customizable, but I can't change images for example.
I would like to replace the small image displayed when a field is not completed by an other one using Javascript.
This is the HTML code with the original image :
<img class="incorrect-img" count="1" src="http://www.detailsdetails.eu/images/newimg/incorrect.gif"></img>
I'm trying with this Js code but it's not working...
$(document).ready(function () {
document.getElementsByClassName("incorrect-img").src="MYIMAGE.gif";
});
Does anyone know what I'm doing wrong?
Maybe it's because I'm trying to change an image from a class, maybe it only works with ID ? I can't change the class by ID...
document.getElementsByClassName("incorrect-img") returns an HTMLcollection which is like an array but not quite.
Luckily you can loop over it like you would with an array:
var elems = document.getElementsByClassName("incorrect-img");
for (var i = 0; i < elems.length; i+= 1) {
elems[i].src = "MYIMAGE.gif";
}
If you want to use jQuery
$(document).ready(function () {
$( ".incorrect-img" ).each(function( index ) {
$(this).attr('src', 'MYIMAGE.gif');
});
});
Since you're already using jQuery, instead of:
document.getElementsByClassName("incorrect-img").src="MYIMAGE.gif";
You can use:
$(".incorrect-img").attr("src", "MYIMAGE.gif");
document.getElementsByClassName() returns the elements of array which are matched with class selector, In your case there is only one image so 0 index would be fine for access the first element. like this
document.getElementsByClassName("incorrect-img")[0].src="MYIMAGE.gif";
For inormationa about `getElementsByClassName()
thanks a lot.
I combined your answers.
here is my final code :
$(window).load(function() {
var image = $(".incorrect-img");
for (var i = 0; i < image.length; i++) {
image[i].src="incorrect_2.gif";
}
});