Modify the src to data-src JavaScript [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
How Replace All img src With data-src for Lazy Load Without jQuery
(1 answer)
Closed 1 year ago.
I want to replace src from data-src and I have the script but it's not working properly. Please modify this given script.
This is the script which I want to load before loading images but it's not working properly so please fix this.
var region = document.getElementsByClassName("content");
if (region) {
var img = region.getElementsByTagName("img");
for (var i = 0; i < imgEl.length; i++) {
if (imgEl[i].getAttribute('src')) {
imgEl[i].setAttribute('data-src', imgEl[i].getAttribute('src'));
imgEl[i].removeAttribute('src');
}
}
}
<div class='content'> <img src="img.jpg" alt="img"> </div>

A nice method for do that is using querySelectorAll for get a return of NodeList and can iterate with forEach callback, here an example:
var region = document.querySelectorAll(".content");
//console.log(region);
if (region) {
region.forEach(function(element) {
let img = element.querySelectorAll("img");
img.forEach(function(elementx, index) {
let x = elementx.getAttribute('src');
if (x) {
elementx.dataset.src = x;
elementx.removeAttribute('src');
}
});
});
}
<div class="content">
<p>Abcd</p>
<img src="something.jpg" />
<p>Efgh</p>
<img src="something2.jpg" />
<p>Ijkl</p>
<img src="something3.jpg" />
</div>
<div class="content">
<p>Abcd</p>
<img src="something4.jpg" />
<p>Efgh</p>
<img src="something5.jpg" />
<p>Ijkl</p>
<img src="something6.jpg" />
</div>

var region = document.getElementsByClassName("content");
​
for (var x = 0; x < region.length; x++) {
var imgs = region[x].getElementsByTagName("img");
​
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].getAttribute('src')) {
imgs[i].setAttribute('data-src', imgs[i].getAttribute('src'));
imgs[i].removeAttribute('src');
}
}
}

Related

How to get a list of the elements in a given div using JavaScript

In a given id of a <div> I need to get a list of all the elements which are in that div.
My goal is to get a list of all elements in the given div and loop over them hide everyone except the first one.
Example:
<div id="RandomId">
<img src="src_1" />
<img src="src_2" />
<img src="src_3" />
.
.
.
<img src="src_n" />
</div>
<script>
function handleImages(divID) {
const div = document.getElementById(DivID);
if(div) {
const Elements = // Here, I need the list;
for (let i = 0; i < Elements.length; i++) {
if (i == 0) {
continue;
}
else {
Elements[i].style = "display:block";
}
}
}
return null;
}
</script>
You could also use querySelectorAll:
const Elements = document.querySelectorAll('#RandomId > img')
You need to use Element.children to get the list of elements inside the div.
That's very easy to do when you're using native JavaScript. Use the following:
<script>
function handleImages(divID){
const div = document.getElementById(DivID);
if(div){
const Elements = div.children //Here, I need the list;
for (let i = 0; i < Elements.length; i++){
if (i == 0) { continue; }
else {Elements[i].style = "display:block";}
}
}
return null;
}
</script>
More details about Element.children.
You can use querySelectorAll to get rid of first child as:
function handleImages(id) {
const allChildren = [...document.querySelectorAll(`#${id} > img`)];
allChildren.forEach(
(imgChild, index) =>
(imgChild.style.display = index === 0 ? "block" : "none")
);
}
handleImages("RandomId");
<div id="RandomId">
<img src="https://picsum.photos/200/300" />
<img src="https://picsum.photos/200/300" />
<img src="https://picsum.photos/200/300" />
<img src="https://picsum.photos/200/300" />
</div>

How to insert image src with while loop in javascript

I want to insert image src with while loop in javascript
$(document).ready(function(){
var i=1;
while(i <= 40)
{
document.getElementByClassName("fruit").src += "path" + i + ".png";
i+=1;
}
});
<img class="img-responsive" src="path/1.png" />
<img class="img-responsive" src="path/2.png" />
<img class="img-responsive" src="path/3.png" />
...
<img class="img-responsive" src="path/40.png" />
How to create this series with javascript
It's better to look at the collection of elements with the class name first, rather than evaluate the collection with each pass through the while loop.
$(document).ready(function(){
var i = 0;
var elementCollection = document.getElementsByClassName('img-responsive');
var max_i = elementCollection.length;
while(i < 40 && i < max_i) {
elementCollection[i].src = "path/" + i + ".png";
i+=1;
}
});

Sorting images by their ID [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to sort LI's based on their ID
I have a div that is dynamically populated with various images and looks something like:
<div id="images">
<img id="img1" src="..." />
<img id="img3" src="..." />
<img id="img2" src="..." />
<img id="img6" src="..." />
<img id="img5" src="..." />
<img id="img4" src="..." />
</div>
Using javascript and jQuery, i need to sort the images into order of ID but i'm struggling. Heres what I've got so far:
var toSort = $('#images').children;
toSort = Array.prototype.slice.call(toSort,0);
toSort.sort(function(a,b){
var aord = +a.id.substr(6);
var bord = +b.id.substr(6);
return aord - bord;
});
var parent = $('#images');
parent.innerHTML="";
for(var i=0, l = toSort.length; i<l; ++i){
parent.appendChild(toSort[i]);
}
How close am I? What am I doing wrong? Thanks guys.
var imgs = $('#images img');
imgs.sort(function(a, b) {
return a.id > b.id;
});
$('#images').html(imgs);
​
DEMO
OR
var imgs = $('#images img');
imgs.sort(function(a, b) {
return +a.id.replace('img','') - +b.id.replace('img','');
});
$('#images').html(imgs);
DEMO
Edition with your code:
var parent = $('#images'),
children = parent.children(),
toSort = Array.prototype.slice.call(children, 0);
parent[0].innerHTML = ""; //or parent.empty();
toSort.sort(function(a, b) {
var aord = +a.id.substr(3);
var bord = +b.id.substr(3);
return aord - bord;
});
for (var i = 0; i < toSort.length; i++) {
parent.append(toSort[i]);
}
DEMO
var elem = $('#images'),
imgs = elem.find('img');
imgs.sort(function(a, b) {
return a.id.toUpperCase().localeCompare(b.id.toUpperCase());
});
$.each(imgs, function(idx, itm) { elem.append(itm); });
FIDDLE
I think #thecodeparadox version is better but here is your code corrected a little bit. I changed img to span to make it more visible.
http://jsfiddle.net/whnyn/

Export/Retrieve unclickle links of images via javascript?

I use this to retrieve clickable links in a webpage:
javascript:(function(){as=document.getElementsByTagName(%22a%22);str=%22<ul>%22;for(i=0;i<as%20.length;i++){str+=%22<br><a%20href=%22+as[i].href+%22>%22+as[i].href+%22</a>\n%22}str+=%22</as></ul>%22;with(window.open()){document.write(str);document.close();}})()
But how do i retrieve unclickable image links in a web page? i don't have any knowledge in javascript :D
If you are not using any js frameworks like jQuery/ExtJS etc, then you resort to this solutin:
<input type="button" value="Calculate" onclick="checkImages()"/>
Google
<img src="1" /> sss
<span><img src="2" /> sss</span>
<img src="3" />
<img src="4" />
<div id="outputDiv">
</div>
<script type="text/javascript">
function checkImages()
{
var str="<ul>";
var imgs = document.getElementsByTagName("IMG");
var len = imgs.length;
for(var i=0; i<len; i++)
{
var img = imgs[i];
//console.log("Checking" + img);
if(!hasParentAnchor(img))
{
str+="<li><img src="+img.src+"/></li>";
}
}
document.getElementById("outputDiv").innerHTML = str;
}
function hasParentAnchor(el)
{
if(!el.parentNode || !el.parentNode.tagName) return false;
else if(el.parentNode.tagName.toUpperCase() == "A") return true;
else return hasParentAnchor(el.parentNode);
}
</script>

jquery: Paste a set of elements over another set of elements / merging elements

I have 2 sets of elements:
<div class='container container1'>
<div class='colors'>
<div class='blue'></div>
<div class='red'></div>
</div>
<div class='drinks'>
<div class='soda'>coke</div>
<div class='juice'></div>
</div>
</div>
<div class='container container2'>
<div class='cars'>
<div class='sedans'></div>
<div class='vans'></div>
</div>
<div class='drinks'>
<div class='soda'>mountain dew</div>
<div class='coffee'></div>
</div>
</div>
I want to paste container1 over container2 such that any replacements are over written and any uniques to each container are put left alone and put together.
The result should be:
<div class='container container-result'>
<div class='colors'>
<div class='blue'></div>
<div class='red'></div>
</div>
<div class='cars'>
<div class='sedans'></div>
<div class='vans'></div>
</div>
<div class='drinks'>
<div class='soda'>coke</div>
<div class='juice'></div>
<div class='coffee'></div>
</div>
</div>
The elements can have any arbitrary hierarchy / depth. What's the best way to do this?
Thanks in advance.
Since your question is tagged jQuery here's a slightly shorter answer using that library:
function copy(from, to) {
from.children().each(function() {
var match = to.children("." + this.className.split(' ').join('.'));
if(match.length) {
if(match.children().length == 0) {
match.replaceWith(this);
} else {
copy($(this), match);
}
} else {
to.append(this);
}
}).end().remove();
from.remove();
}
Then you'd just call it like this:
copy($(".container1"), $(".container2"));
You can give it a try here, the result is:
<div class="container container2">
<div class="cars">
<div class="sedans"></div>
<div class="vans"></div>
</div>
<div class="drinks">
<div class="soda">coke</div>
<div class="coffee"></div>
<div class="juice"></div></div>
<div class="colors">
<div class="blue"></div>
<div class="red"></div>
</div>
</div>
Note that the class name is still container2 if you want to replace that just add this to switch the class after the copy() call:
$(".container2").toggleClass("container2 container-result");
The match is based on all classes the element contains, so if an element has class="car blue" and there's a corresponding class="blue car" it'll choose that one to overwrite.
This isn't the most efficient route since you're firing up the selector engine on the children each iteration, but unless you're doing lots of elements, it should be pretty quick.
With regard to unique merging I can't help you there, but if your app by any chance happens to be in PHP then you can use php's array_merge function to merge them before outputting the HTML.
ReplaceWith is a nice jquery function to replace aka "paste" over, it may will help you with half of your solution.
This appears to do what you wanted:
<div class='container container1'>
<div class='colors'>
<div class='blue'></div>
<div class='red'></div>
</div>
<div class='drinks'>
<div class='soda'>coke</div>
<div class='juice'></div>
</div>
</div>
<div class='container container2'>
<div class='cars'>
<div class='sedans'></div>
<div class='vans'></div>
</div>
<div class='drinks'>
<div class='soda'>mountain dew</div>
<div class='coffee'></div>
</div>
</div>
<div class='container container-result'>
</div>
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getContainerArray(containers, level) {
level = level || 0;
var result = [];
for (var i=0; i<containers.length; ++i) {
var el = containers.eq(i);
var obj = { "class": el.attr("class") };
if (level == 0) {
obj.items = getContainerArray(el.children("div"), 1);
} else {
obj.text = el.text();
}
result.push(obj);
}
return result;
}
function mergeContainers(containerArray) {
var result = [];
function indexOfClass(name) {
for (var i = 0; i < result.length; ++i) {
if (result[i]["class"] == name) {
return i;
}
}
return -1;
}
for (var i = 0; i < containerArray.length; ++i) {
var obj = containerArray[i];
var name = obj["class"];
var index = indexOfClass(name);
if (index < 0) {
result.push(obj);
} else if (obj.items != null) {
result[index].items = mergeContainers(new Array().concat(result[index].items, obj.items));
}
}
return result;
}
function getHtml(objArray) {
var result = [];
for (var i = 0; i < objArray.length; ++i) {
var obj = objArray[i];
result.push("<div class=\"", obj["class"], "\">");
if (obj.text != null && obj.text != "") {
result.push(obj.text);
}
if (obj.items != null) {
result.push(getHtml(obj.items));
}
result.push("</div>");
}
return result.join("");
}
var html = getHtml(mergeContainers(getContainerArray($("div.container1>div,div.container2>div"))));
$("div.container-result").append(html);
</script>
This answer:
Does exactly what you asked for.
Handles repeated mergings, if div class container-result already exists.
Merges any number of container divs.
Uses jQuery and is more efficient than some other solutions.
See it in action at jsfiddle.net.
/*--- Get all "container" divs but exclude any "container-result" divs.
*/
var zContainers = $("div.container").not ("div.container-result");
if (zContainers && zContainers.length)
{
//--- Get or create the results div.
var zResultDiv = $("div.container-result");
if (!zResultDiv || !zResultDiv.length)
{
zResultDiv = zContainers.parent ().append ("<div class='container container-result'></div>");
zResultDiv = $("div.container-result");
}
//--- Move the container's contents to the master container, preserving order.
zContainers.each (function () {$(this).children ().appendTo (zResultDiv);} )
//--- Kill the old container(s).
zContainers.remove ();
RecursivelyMergeDivsByClass (zResultDiv);
}
function RecursivelyMergeDivsByClass (jNode)
{
/*--- Get a list of the direct-child div's class names.
Sort and winny out a list of duplicates.
*/
var zDirectChildDivs = jNode.find ("> div");
var aClassList = zDirectChildDivs.map (function () {return this.className;} ).get ();
aClassList.sort ().unshift (0);
for (var J = aClassList.length-1; J > 0; J--)
if (aClassList[J] != aClassList[J-1]) aClassList.splice (J, 1); // Delete items without duplicates.
aClassList.splice (0, 1);
/*--- For any duplicates, copy the contents into the first instance, preserving order.
For exact duplicate nodes, the first (oldest) version is kept and the remaining are discarded.
*/
for (var J = aClassList.length-1; J >= 0; J--)
{
var zDupClasses = zDirectChildDivs.filter ("." + aClassList[J]);
var zFirstDiv = zDupClasses.first ();
zDupClasses = zDupClasses.not (zFirstDiv);
zDupClasses.each (function () {$(this).children ().appendTo (zFirstDiv);} )
zDupClasses.remove ();
RecursivelyMergeDivsByClass (zFirstDiv)
}
}

Categories