jQuery: Giving elements in selector individual attributes - javascript

I want to replace all svg images on my page with other svg images with the same name, but in a different directory.
Specifically, the current images are in the img directory, I want to replace the source of the images to img/icon-black.
I get all the svg elements with the following selector:
$.svgSelector = $(document).find('img[src$=".svg"]');
I calculate the new sources with the following:
var newSources = $.svgSelector.map(function(){return $(this).attr("src");}).get();
for(var i = 0; i < newSources.length; i++) {
newSources[i] = newSources[i].replace(/^.*[\\\/]/, '');
newSources[i] = "img/icon-black/" + newSources[i];
}
The problem arises when I want to assign the new sources to the individual elements in the selector.
I want to do something like this:
for(var j = 0; j < newSources.length; j++) {
$.svgSelector[i].attr("src", newSources[i]);
}
i.e. assign the source of each individual element's in the selector to its corresponding new source.
This way does not work, however. .attr() only returns the first src in the selector, and you cannot use it on individual elements of the selector like this either. I have also tried the .each() function but I cannot figure it out.
How do I solve this?

Instead of having to map all the src attributes to a new array, and then iterating through the array to replace the values, and then rewriting the sources in yet another loop, you can all do it in a single iterative block:
$.svgSelector = $(document).find('img[src$=".svg"]');
$.svgSelector.each(function() {
newImageSrc = "img/icon-black/" + $(this).attr('src').replace(/^.*[\\\/]/, '');
$(this).attr('src', newImageSrc);
});
Even better: the .attr() function actually takes a callback. In that sense, you can even condense it further:
$(document).find('img[src$=".svg"]').attr('src', function(i, src) {
return "img/icon-black/" + src.replace(/^.*[\\\/]/, '');
});

Related

getElementsByTagName is not returning all the images why?

I'm trying to get all the img element from some website.
I opened the chrome dev tools console and put the following code which is,
var imgs = document.getElementsByTagName("img");
var i;
for (i = 0; i < imgs.length; i++) {
console.log(imgs[i]);
}
Yes, code works and returns lists of images in console but not fully.
I noticed that some img elements are not returned.
the parts that is not returened is in the following image.(the links is here)
I really wonder why these guys are not returned. Why is that?
As I said in the comment, there are no <img> elements, those are <a> elements with a css background image.
If you want to get those image urls, simply select the <a> elements, access their background-image css property and extract the urls:
var aElems = document.querySelectorAll(".J_Prop_Color a");
var images = [];
for(var i = 0; i < aElems.length; i++) {
images.push(aElems[i].style.backgroundImage.replace("url(", "").replace(")", "").replace(/\"/gi, ""))
}
console.log(images);
The .replace("url(", "").replace(")", "").replace(/\"/gi, "") part is used to remove the surrounding url("...") as per this SO answer.
Note 1: The resulting urls appear to be protocol-relative urls, where they start with // rather than an explicit protocol like https://, you may want to prepend "https:" to them before using them.
Note 2: The resulting urls are of thumbnails rather than of the full-sized images, remove the _(number)x(number).jpg part of those urls by using this replace: replace(/_\d+x\d+\.[^.]+$/, "") to get the full-size image urls:
images.push("https:" + aElems[i]
.style.backgroundImage
.replace("url(", "").replace(")", "").replace(/\"/gi, "")
.replace(/_\d+x\d+\.[^.]+$/, "")
);
The problem if you open the console and inspect the elements is like someone mention in the comments that there are no image tags, if you check the console, you will see:
a div.
You want to do:
var imgs = document.getElementsByID(IDVALUES);
var i;
for (i = 0; i < imgs.length; i++) {
console.log(imgs[i]);
}
the id is stored in the div id something like 'ks-component-??'
Most likely the answer above will not give you want since you want multiple images you would want to create an array and push the corresponding elements to it.
var img1 = ....
var img2 = etc....
....
let arr = [];
arr.push(img1);
arr.push(img2);
....
for (i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Where the ... means the list or all the variables you need

Get element attribute from array

The objective is to create multiple sliders on the page by linking the slider to something. The slider must be activated by clicking or hovering the slider anchor. sliderList would be a array for making this process easier so i wouldn't have to link each other manually on the configs js file.
I need to get the attribute value from a element that is inside an array. In this case, holder is the array from where I want to extract the attribute value from the current array element. I tried doing this:
var holder = $('[slider-select]');
for (var i = 0; i < holder.length; i++) {
var sliderList = $('[slider-target='
+holder[i].attr('slider-select')
+']');
}
It looks like +holder[i].attr('slider-select') isn't working. I'm learning JavaScript/Jquery and it's crazy how things goes wrong even when it makes all sense, lol. Let me know if I wasn't clear enough.
The function attr is a built-in function from jQuery, it's a shorthand of function getAttribute and setAttribute.
In your case you want to do this:
var holder = $('[slider-select]');
for (var i = 0; i < holder.length; i++) {
var test = holder[i];
var sliderList = $('[slider-target=' + holder[i].getAttribute('slider-select') + ']');
} ^
A good approach is to use the jQuery built-in functions, so you can use this:
$('[slider-select]').each(function() {
var sliderList = $('[slider-target=' + $(this).attr('slider-select') + ']');
}); ^
Resources
.attr()
getAttribute
setAttribute
.each()
holder[i] contains a plain DOM element, but you're trying to use the jQuery attr method on it. You need to convert it into a jQuery object $(holder[i]) (or else use the native getAttribute on the DOM element):
var holder = $('[slider-select]');
for (var i = 0; i < holder.length; i++) {
// Splitting this up a bit just to make it more readable:
var val = $(holder[i]).attr('slider-select'); // instead of holder[i].attr(...)
var sliderList = $('[slider-target="' + val + '"]');
// confirm we got the element:
console.log(sliderList.text());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div slider-select="A">A</div>
<div slider-select="B">B</div>
<div slider-select="C">C</div>
<div slider-target="A">a</div>
<div slider-target="B">b</div>
<div slider-target="C">c</div>
The attr method is not a function on the JS element object. You'll want to wrap it in jquery to retrieve attribute values instead. For instance
$(holder[i]).attr("slider-select")

How to optimize or make this dynamic (html javascript)

i'm still new in html javascript. I want to ask can i use for loop to optimize or make this dynamic
var port = [];
port[0]=$('#slcPort_0').val();
port[1]=$('#slcPort_1').val();
port[2]=$('#slcPort_2').val();
port[3]=$('#slcPort_3').val();
port[4]=$('#slcPort_4').val();
i used this code in function to retrieve data from html form
thanks
You could use:
// selects all the elements whose 'id' starts-with "slcPort_":
var port = $('[id^=slcPort_]').map(function(){
// returns the value from those elements:
return this.value;
// converts to an array:
}).get();
This isn't guaranteed to be in numerical order, though it will be in order of the appearance of those elements in the DOM.
References:
Attribute-starts-with ([attribute^=value]) selector.
get().
map().
Simply, you can do the following:
var port = Array();
for (i = 0; i < 5; i++){
port[i] = $("#slcPort_"+i).val();
}
DEMO: http://jsbin.com/yiyaruweja/1/
It might make more sense to give all those elements a class, like slcPort. Then something like
var port = [];
$.each($('.slcPort'), function(index,value) {
port[index] = $(value).val();
});
Much prettier. Plus all those elements are related anyways, so just class em up.
$.each documentation

Replace string of text javascript

Im trying to replace a string of text for another string of text here is my code plus js fiddle
HTML
<div class="label">Rating:</div>
<div class="data rating">****</div>
Javascript
var str=document.getElementsByClassName("data" ,"raiting").innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data", "raiting").innerHTML=n;
Demo
http://jsfiddle.net/sgGQz/1/
document.getElementsByClassName() method returns, as its name suggests, a collection (HTMLCollection) of elements, not a single one -even if there's just a single element with the given classname(s) in DOM.
You need to go through each of them in order to make such a replacement. For example:
var elements = document.getElementsByClassName("data rating");
for (var i = 0, l = elements.length; i < l; i++) {
elements[i].innerHTML = elements[i].innerHTML.replace(/\*/g, 'star');
}
JSFiddle.
Alternatively, if you know for sure that there should be only a single element, you can assign it directly:
var elementToAdjust = document.getElementsByClassName("data rating")[0];
// ...
If you only have one occurrence of the element this will work:
var str=document.getElementsByClassName("data rating")[0].innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data rating")[0].innerHTML=n;
If multiple data rating elements exist use:
var elems =document.getElementsByClassName("data rating");
for(var i = 0; i < elems.length; i++){
elems[i].innerHTML = elems[i].innerHTML.replace(/\*/g,"star");
}
Both method correct some flaws in the original code.
First, rating was misspelled in the argument passed to getElementsByClassName. Second, getElementsByClassName() uses class names delimited by spaces to select elements with multiple classes, instead of multiple arguments. Get elementsByClassName returns an array of elements which must be iterated through.
JS Fiddle: http://jsfiddle.net/sgGQz/5/
You need to check again for getElementsByClassName,It returns node-List, so you can do like this and You can loop through then after each element and set your value
var str=document.getElementsByClassName("data" ,"raiting")[0].innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data", "raiting")[0].innerHTML=n;
Here is the example as you have only one occurance

Random element from an array of images and their respective links on page refresh

I've got an unordered list of images. I'd like for each of those images to have an href attribute (since I would like to use a lightbox-popup to display the correlating image when clicked), but for each image to be random when the page is refreshed.
In short, for each image coupled with its href to be random, but the order of the ul to stay the same. What would be a way of achieving this?
var img_array = []; //assuming your array is called this and full of porn pictures
//fisher-yates algorithm. Google it
(function(){
var tmp, current, top = img_array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = img_array[current];
img_array[current] = img_array[top];
img_array[top] = tmp;
}
})();
//target html element where the images are appended
var target = document.getElementById('someTargetDiv');
for(var i=0, len=img_array.length; i<len; i++){
var link = document.createElement('a'),
img = document.createElement('img');
link.setAttribute('href', img_array[i]);
img.setAttribute('src', img_array[i]);
link.appendChild(img);
target.appendChild(link);
}
This is not an optimized way of doing this kind of operation. I've made it slightly more verbose for your understanding.
The biggest mistake with this code is the constant creation of many different elements and appending them to the DOM one at a time. What should really be done is to build a string of generated html, and changing the innerHTML of a target div in one operation.
var html = [];
for(var i=0, len=img_array.length; i<len; i++){
html.push('<img src="'+ img_array[i] +'">');
}
target.innerHTML = html.join('');
Hopefully I get this right.
With jQuery you could do it like this jsfiddle:
$('ul').children('li').sort(function() {
return Math.round(Math.random()); // randomly get 0 or 1
}).appendTo('ul');
Doing it with PHP on server side would make more sense, but since you have no db resource or so, you'd have to make a static array of image:link pairs then shuffle it and generate a random list.
UPDATE
Maybe this comes closer to a solution:
jsfiddle
var contents = new Array(),
$list = $('li');
$list.each(function() { contents.push($(this).children()); });
contents.sort(function() {
return 0.5 - Math.random();
});
$list.each(function() {
$(this).append(contents.shift());
});

Categories

Resources