is it possible to give a div an Id from image title within. so that any image that is uploaded into an empty div without an id the div.id will copy the images title
using js
example pass OSCAR up to div id
<div id="">
<img src="images/image/image.png" title="OSCAR"/>
</div>
Considering this question is not tagged jQuery and all img should have a title attribute.
http://jsfiddle.net/eC3DE/
var images = document.querySelectorAll('div > img'),
i = 0,
len = images.length,
img;
for (; i < len; i++) {
img = images[i];
img.parentNode.id = img.title;
}
Please note that you will have to run the code everytime an image is added to the DOM. If you are using a modern browser that supports the MutationObserver object, you could use it to detect when new images are added.
Include jQuery and use this code for set div id:
$(function(){
$("div > img[title]").each(function(){
var parent = this.parentNode;
if(!parent.id)parent.id=this.title;//if id is empty, set id from title
})
})
Or you can take div so:
$("img[title='OSCAR']").parent("div");
Related
I've been working with Javascript for a little bit now. My code below has various pictures defined as an object. Now I want to put these images as <img> inside <li> tags. However, I am experiencing some difficulty with this.
for (var i = 0; i < pictures.length; i++){
var newImage = document.createElement('img')
newImage.setAttribute('class', 'image-item')
newImage.setAttribute('alt', pictures[i].name)
newImage.src = pictures[i].url
var liItem = document.createElement('li')
liItem.innerHTML = newImage
document.getElementById('pictures').appendChild(liItem)
console.log(liItem)
}
Any idea on how to resolve this? The result has to look like this:
<li><img src="picture1.jpg" alt="loremipsum"></li>
Right now console tells me the following:
Change liItem.innerHTML = newImage to liItem.appendChild(newImage)
The innerHTML property sets or returns the HTML content (inner HTML) of an element. so you should change liItem.innerHTML = newImage to liItem.appendChild(newImage)
Everything is working, but when I want to add background-image, to different elements, it's just putting last image from array, and set css backgorund to all of them with that last image.
$.get('con.php',function(data) {
var data = JSON.parse(data);
for(i = 0; i < data.length; i++) {
var div = "<div class='nemkec-dev' id='"+data[i].id+"'>"+"<h1>"+ data[i].text+"</h1>"+"<p>"+
data[i].text2+"</p>"+"<img src='images/"+data[i].image+"'/>"+"</div>";
$('body').append(div);
var image = data[i].image;
}
$.each(data, function(i, dat) {
$('.nemkec-dev').css('background-image','url(images/'+dat.image+')');
});
It shows image as element. But, when I want to set css rule it's not working.
Just appending last-image to all for background.
When creating var div you can create an inline style var div = "<div style='background-image: url(images/"+data[i].image+")'...
I am pretty sure you want to iterate over $('.nemkec-dev') elements. What you are doing now is iterating over background images and setting background image for all of .namkec-dev divs at once. So natural outcome is that after this script ends you have all .nemkec-dev elements with the last background image.
You can go with Michael Coker solution and use them in line with other variables, or do something like this:
var i = 0;
$('.nemkec-dev').each(function() {
$(this).css('background-image', data[i].image);
i++;
});
I have a problem on swapping two images (from div vignette, to div gallerie).
Situation: I click on a little image, then It swap it place with the big image.
Here is the HTML
<div id="gallerie">
<img id="first" src="http://lorempicsum.com/futurama/620/350/2"><br/>
<div id="vignette">
<img class="second" src="http://lorempicsum.com/futurama/100/100/6">
<img class="second" src="http://lorempicsum.com/futurama/100/100/4">
<img class="second" src="http://lorempicsum.com/futurama/100/100/3">
<img class="second" src="http://lorempicsum.com/simpsons/100/100/2">
<img class="second" src="http://lorempicsum.com/simpsons/100/100/1">
<img class="second" src="http://lorempicsum.com/simpsons/100/100/4">
</div>
</div>
Here is the JavaScript
document.getElementById("vignette").addEventListener('click', changeSrc);
function changeSrc(e) {
var images = document.getElementsByClassName("second").src;
var first = document.getElementById("first").src;
s = e.target.src;
first = s;
console.log("click");
}
For the moment, I don't want to use jQuery.
Solution on some websites use images directly on the JS code with an "if" cascade. I don't think that's efficient for me.
I can propose to use a for loop with the "var image" but I don't know how to use the e.target.
I search to perform my code, so could you explain me why I was wrong?
Here is the JsFiddle
https://jsfiddle.net/ws3f4san/
I can give you more details if you want.
In this block of code, you're not actually setting the source, you're just overwriting the source you've stored as a string in the first variable.
var images = document.getElementsByClassName("second").src;
var first = document.getElementById("first").src;
s = e.target.src;
first = s;
first = s; will have no effect on the page since you're just changing a JS variable, not a dom element.
You need to edit the actual source attribute, you can do so by storing the dom element instead of the initial src value in the first variable, like so:
var images = document.getElementsByClassName("second").src;
var first = document.getElementById("first"); // Store the dom element, not the string value
s = e.target.src;
first.src = s; // Now assign the new value to the src attribute of your stored dom element
Edited having looked more thoroughly at what you're trying to do, you can swap the src's like this:
function changeSrc(e) {
// Get the initial dom element
var mainItem = document.getElementById("first");
// Save it's src before it's changed
var mainItemImage = mainItem.src;
// Get the clicked element
var clickedItem = e.target;
// Set the first image to the second image
mainItem.src = clickedItem.src;
// Set the second image to the first image's original value (which has now changed)
clickedItem.src = mainItemImage;
}
I'm trying to replace multiple links but only the first one is replaced,
all the other remain the same.
function rep(){
var text = document.querySelector(".link").querySelector("a").href;
var newText = text.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
document.querySelector(".link").querySelector("a").href = newText;
}
Any suggestions?
It's multiple a href links inside .link elements which I'm talking about.
Your mistake is in using querySelector, so document.querySelector(".link").querySelector("a") literally translates to: get me the first a inside the first .link;
Use querySelectorAll; and you can combine the two selectors:
Vanilla JS:
[].forEach.call(document.querySelectorAll('.link a'), function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
Or, since you'll select items more often, a little utility:
function $$(selector, ctx){
return Array.from((ctx && typeof ctx === "object" ? ctx: document).querySelectorAll(selector));
}
$$('.link a').forEach(function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
})
Or in jQuery:
$('.link a').each(function(){
this.href = this.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
This doesn't use JQuery, and I've changed your regular expression to something that made more sense for the example. It also works when you run the snippet.
function rep() {
var anchors = document.querySelectorAll(".link a");
for (var j = 0; j < anchors.length; ++j) {
var anchor = anchors[j];
anchor.href = anchor.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
rep();
a[href]:after {
content: " (" attr(href)")"
}
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
Edit: Expanded example showing multiple anchor hrefs replaced inside multiple link classed objects.
Edit2: Thomas example is a more advanced example, and is more technically correct in using querySelectorAll(".link a"); it will grab anchors in descendants, not just children. Edited mine to follow suite.
If you intend to only select direct children of link class elements, use ".link>a" instead of ".link a" for the selector.
Try using a foreach loop for every ".link" element. It seems that
every ".link" element have at least 1 anchor inside, maybe just one.
Supposing every .link element has 1 anchor just inside, something like
this should do:
$('.link').each(function(){
// take the A element of the current ".link" element iterated
var anchor = $(this).find('a');
// take the current href attribute of the anchor
var the_anchor_href = anchor.attr('href');
// replace that text and achieve the new href (just copied your part)
var new_href = the_anchor_href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/,'http://google$2com');
// set the new href attribute to the anchor
anchor.attr('href', new_href);
});
I did't test it but it should move you to the way. Consider that we
could resume this in 3 lines.
Cheers
EDIT
I give the last try, looking at your DOM of the updated question and using plain javascript (not tested):
var links = document.getElementsByClassName('link');
var anchors = [];
for (var li in links) {
anchors = li.getElementsByTagName('A');
for(var a in anchors){
a.href = a.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
I suggest to read the following post comment for some cooler methods of looping/making stuff foreach item.
How to change the href for a hyperlink using jQuery
I have a div with id="images".
The div contains some images that are each wrapped in an anchor tag with no target attribute.
I'd like to insert script into my page that pulls a reference to each of these anchor elements and ads a target="new" attribute to them (in the runtime) so that when they are clicked they each open in a new window.
I don't want to hardcode the target attributes on the anchor tags. This is a post deployment workaround. I'm not using jquery in this application.
<div id="images"><img src="foo.png" />...etc </div>
No jQuery required! You can do this easily using native DOM methods:
// Find all the anchors you want to modify
var anchors = document.getElementById('images').getElementsByTagName('a'),
i = anchors.length;
// Add the target to each one
while(i--) anchors[i].target = "new";
You can traverse all the anchor elements inside your div, first by looking up the div itself, and then you can use the element.getElementsByTagName method:
var imagesDiv = document.getElementById('images'),
images = imagesDiv.getElementsByTagName('a');
for (var i = 0, n = images.length; i < n; i++) {
images[i].target = "_blank";
}
function replaceAllAnchors(Source,stringToFind,stringToReplace){
//sample call: body=replaceAllAnchors(body,'<a ','<a target="_blank" ');
var temp = Source;
var replacedStr="";
var index = temp.indexOf(stringToFind);
while(index != -1){
temp = temp.replace(stringToFind,stringToReplace);
replacedStr=replacedStr+temp.substr(0,temp.indexOf("/a>")+3);
temp=temp.substr(temp.indexOf("/a>")+3);
index = temp.indexOf(stringToFind);
}
replacedStr=replacedStr+temp;
return replacedStr;
}
Why can't you use jQuery? I've added this here for other people who google.
It's 1 line of code in a loop:
$('#images a').each(function(){ $(this).attr('target', '_blank'); });
Now isn't that much more simple? Use jQuery if you can.