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";
}
});
Related
I am trying to remove an element based on type of attribute. It isn't working for some reason.
The element in question is this:
<p style="width:250px;font-size:11px;text-align:left;margin-left:1.2ex;margin-top:0px;margin-bottom:0px;line-height:1.15em;">– in Europe<span style="font-size:8px;"><span style="white-space:nowrap;"> </span></span>(<span style="font-size:9px;">green & dark grey</span>)<br>
– in the European Union<span style="font-size:8px;"><span style="white-space:nowrap;"> </span></span>(<span style="font-size:9px;">green</span>)</p>
I am trying to remove it this way - item is a container element.
$(item).find("p").filter("[style]").remove();
There are no other <p> tags with the attribute style, however this doesn't appear to remove it.
Other code, like this, works fine:
$(item).find(".reference").remove();
How do I remove all p tags with the style attribute from the item element?
This is how item is created:
$.get(link, 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];
The link variable is a link to wikipedia.
Maybe try this:
$.each(item.children('p'), function(index) {
if ($(this).attr('style')) {
$(this).remove();
}
});
item refers to p element itself. you don't have to find p in item:
$(item).filter("[style]").remove();
after re-looking over your question ,
$(item).find("p").filter("[style]").remove();
is perfectly valid , instead of trying to come up with alternative ways to write it , find out what is wrong with item, because it is not what you think it is if above code is not working
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);
For instance , there is a
img id = img_1 , img_2 , img_3 , img_4 and so on..
However, I don't know the exact number of divs
$('#img_').remove
seems not working
So , How to remove all the img that has an id "img_"? Thanks.
You can use the attribute starts with selector to grab the elements you want:
$('[id^="img_"]').remove();
Docs
I suppose this should work:
$('[id^=img_]').remove();
It removes any element with an id that starts with img_
Apply same class to all images which has an id "img_" then use
$('.className').remove();
I hope it help:
for( var i = 0; i < $('img').length; i++) {
if( $($('img')[i]).attr('id').indexOf('img_') !== -1 ) {
$($('img')[i]).remove();
}
}
I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.
I want to know how can I manipulate all the links on a page with javascript. I can get elements by id's with document.getElementById(id), but how can I get the links? And also how can I get all elements with a certain classname? I want to change the color of the link and class elements.
I mean these links:
This is a link
And an example for an element with a class:
<span class="link">This is an element with a class</span>
Please no jquery. I want javascript.
Simple and straightforward (in pure JS too!)
colorLinks("#00FF00");
function colorLinks(hex)
{
var links = document.getElementsByTagName("a");
for(var i=0;i<links.length;i++)
{
if(links[i].href)
{
links[i].style.color = hex;
}
}
}
If it's a class name you're looking for and you know the tag, just use this.
var elements = document.getElementsByTagName("span");
for(var j=0;j<elements.length;j++)
{
if(elements[j].className === "your class here")
{
//do something
}
}
You can also look at getElementsByClassName and querySelectorAll. Both have support in most new browsers.
The pure-JavaScript version isn't all that complicated:
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
if (elements.className.split(/\s+/).indexOf('red') !== -1) {
elements[i].style.color = 'red';
}
}
And for modern browsers:
var elements = document.querySelectorAll('a.red');
[].slice.call(elements).forEach(function(elem) {
elem.style.color = 'red';
});
Update: I still recommend using jQuery, but, if you want to learn how to do it without, I would recommend heading over to this site. This shows how to change link colors when you mouse over the link, but you can easily extrapolate for your specific situation: Javascript Change Link Text Color onmouseover
--
Ottomanlast has a good point about checking out jQuery to help you out with this task (although it can be done without the use of a library). However, just so you have an example of what he is talking about, here is how you could change link colors using jQuery.
$('.linkClass').click(function(){
$(this).css('color', 'green');
});
This example changes the color of a specific link when it is clicked.
$('a').css('color', 'green');
This example will change all the links to a green color.
$('.linkClass').click(function(){
$(this).removeClass('oldClass');
$(this).addClass('newClass');
});
This does the same thing as the first example, but this removes and adds CSS classes that you already have defined elsewhere. (I would recommend this method over just editing the CSS directly.)
Anyway, the point I'm trying to make is that jQuery makes it extremely easy to select and then make changes to the objects within your HTML document. You may want to take a look into it.
You can use document.getElementsByTagName("a"). This function returns an array of the <a> elements in the page. Loop over this array, and use .style.color = "#000000" in each element.
This is how I change all hyperlink colors (normal/hover):
function changeTextHyperlinkColours(inputColorNormal, inputColorHover) {
var sheets = document.styleSheets;
var slen = sheets.length;
for(var i=0; i<slen; i++) {
var rules = document.styleSheets[i].cssRules;
var rlen = rules.length;
for(var j=0; j<rlen; j++) {
if (rules[j].selectorText == 'a') {
rules[j].style['color'] = inputColorNormal;
}
if (rules[j].selectorText == 'a:hover') {
rules[j].style['color'] = inputColorHover;}
}
}
}
}
Also you can embed the link text in the span and change the color
<a href='www.mydomain.com'><span onclick='this.style.color="red"'>Visit Us</span></a>