Can I remove all ID naming with same character in javascript? - javascript

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

Related

jQuery: Adding td elements with one class to tr

First of all I have to find the number of cells with one class, this line works.
var numcells = $('.hidden-td').length
And now I have to find the element with the class .placeholder-style I use this line (only one <tr>have this class):
$(this).find('.placeholder-style')
Now I have to add the same number of var numcellslike <td>inside the <tr>with the clase .hidden-td I think this will be with .addClass('hidden-td').
How can I make this?
Thanks
I'm assuming this is the correct structure you're after... if not, post your HTML so I can amend it but either way, this is how you should do it.
var numcells = $('.hidden-td').length;
var content = $(this).find('.placeholder-style');
for (i = 0; i < numcells; i++) {
content.append('<td class="hidden-td"></td>');
}

Trying to remove element based on type of attribute

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

replacing all images from a class with another image using Javascript

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

How to set filter on div html attribute

I have some divs and one button. Divs have zozo [j] attribute .
When I click on the button, I want their id to be set, but not all divs, just those that have j > k. In fact I want to use a filter.
<div zozo="sim [0]"></div>
<div zozo="sim [1]"></div>
<div zozo="sim [2]"></div>
.
. // and some div else
.
var k = 1;
I know the below code is wrong, but I want something like this:
$("div [zozo='sim ["+ > = k + "]' ]").attr('id' , k+1);
I think you are trying to do:
$("div[zozo^=sim]" ).attr('id' , function(i){ //Use attribute startswith seletor
//return i+1; //return index + 1 as the id
return +$(this).attr('zozo').match(/(\d+)/).pop() + 1;
});
Or just set a common class name to all those elements and use class selector
$("div.myClass" ).attr('id' , function(i){ //Use attribute startswith seletor
return i+1; //return index + 1 as the id
});
Also remember that zozo is not a valid attribute, prefix it with data-* would be more appropriate.
Demo
Ok, so what you'll have to do here is iterate over each element and then do your calculations on the value of each one individually. You're talking about a selector based on some arithmetic calculation - I don't believe that exists.
Here is how I would do it:
var k = 1;
$( "div[zozo^='sim']" ).each( function(){
var value = $( this ).attr( "zozo" ).match(/(\d+)/)[1]; // remove all except the number
value = parseInt( value ); // convert it into an actual number
if ( value >= k ){
// if a condition is met - we update the attribute of the current element
$( this ).attr( "id", (value + k ) );
}
});
I'm using jquery's "attribute starts with" selector here that matches all elements that have a zozo class value that starts with the string "sim".
Note that in your example you're wanting setting the id attribute to k+1. This will always remain the same number and so you'll be setting multiple elements with the same id. You don't want to be doing that. In my example I've made sure that each id attribute is unique.
Check out this demo, you'll see that all but the first red box have their id set.
Assuming the value of data-zozo is always in the same format, and assuming I've understood your question correctly, this should work. You'd want to use a more specific selector, of course.
$('div').click(function () {
var myK = $(this).attr('data-zozo');
myK = myK.charAt(5);
myK = parseInt(myK);
if (myK >= 1) {
$(this).attr('id',myK + 1);
}
});
http://jsfiddle.net/isherwood/5g7yU/
Something like this? WARNING, UGLY CODE
$('#parentdiv > div').each(function () {
var $that = $(this);
var zozo = parseInt($that.attr('zozo').replace('sin[', '').replace(']', ''));
if (zozo >= k)
$that.id = k + 1;
});

Access dynamic generated div id

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.

Categories