dynamically created img tag with jQuery? - javascript

How to create dynamically tag inside table. At first create link then inside link create an img tag like if i have..
<table>
<tr>
<td>
<a>
<img />
</a>
// Add Some more when every time my function is run..? like that
// <a>
// <img/>
// </a>
</td>
</tr>
</table>
Im using this inside function but its didn't work help me.
$(document.createElement("img")).attr('Some attr');

If you mean JQuery by "jquree", then try this:
$('table tr td').append('<img src="/favicon.ico"/>');

Well, I wasn't going to answer that, but I'm not seeing any correct answer (from my POV):
function addElement(tdId) { // Specify the id the of the TD as an argument
$('#' + tdId).append( // Append to the td you want
$('<a></a>').attr({ // Create an element and specify its attributes
'href': '/home',
'title': 'Home'
}).append( // Also append the image to the link
$('<img />').attr({ // Same, create the element and specify its attributes
'src': 'image.png',
'width': '100px',
'height': '100px'
})
) // Close the "append image"
) // Close the "append anchor"
}
Now that is a pure jQuery answer. A javascript answer would be the following:
function addElement(tdId) { // Specify the id the of the TD as an argument
// Create the DOM elements
var a = document.createDocumentFragment('a'),
img = document.createDocumentFragment('img') // See the use of document fragments for performance
// Define the attributes of the anchor element
a.href = '/home'
a.title = 'Home'
// Define the attributes of the img element
img.src = 'image.png'
img.width = '100px'
img.height = '100px'
// Append the image to the anchor and the anchor to the td
document.getElementById(tdId).appendChild(a.appendChild(img))
}
I think the js version is more readable. But that's just my opinion ;o).

$(document).ready(function(){
$('.any_element_you_want').html('<img src="image.png">');
});

var td = $('table tr td');
td.append('<a><img src="whatever.jpg"/></a>');

Make use of jquery and than you cna crate image element like as below
$(document).ready(function(){
var elem = new Element('img',
{ src: 'pic.jpg', alt: 'alternate text' });
$(document).insert(elem); //here you can also make use of `append` method instead of this method
}
or
var img = new Image(1,1); ///params are optional
img.src = ''pic.jpg';

On Every click of button , it will add img tag with image url abc.png
and add to div having id imagediv.
$("button").click(function()
{
var img=$('<img id="dynamic">');
$(document.createElement('img'));
img.attr('src',"abc.png");
img.appendTo('#imagediv');
});

Related

Replace certain html with other html using .html isn't working

I have this html
<div id="items-content">
<p><img class="fr-dib" src="http://i.imgur.com/bEDR9dc.png" data-imgslap="{{image-key}}" style="width: 214px;"></p>
</div>
And i want to replace src="http://i.imgur.com/bEDR9dc.png" with src="http://i.imgur.com/mJyABlG.jpg"
I have the following jquery
$(document).ready(function() {
$('#items-content').html( 'src="http://i.imgur.com/bEDR9dc.png"' ) {
return 'src="http://i.imgur.com/mJyABlG.jpg"';
}
} );
I'm learning JQuery still and I don't know where I have gone wrong. Would appreciate the help.
Update
I plan on using the same method of replacing the image to replace something like data-imgslap= with src=. Basically how do I replace html text 'x' with 'y' (They will only ever be html attributes text being replaced).
Use attr() to solve this problem
$(document).ready(function() { $('#items-content .fr-dib').attr('src', 'http://i.imgur.com/mJyABlG.jpg"'); } );
Or use regular expression
your_string.replace(/(<img\s class\=\"fr-dib\"\ssrc=")(.*?)("\s?\/>)/, "$1http://i.imgur.com/mJyABlG.jpg $3");
Update a DOM img tag's src
You're looking for jQuery's attr() method to update a single attribute's value:
$(document).ready(function() {
$('#items-content .fr-dib').attr('src', 'http://i.imgur.com/mJyABlG.jpg"');
} );
jsfiddle: https://jsfiddle.net/patrickberkeley/0wefe37t/
Update a DOM img src with a value from a data attr
To update one attribute with another attribute's value (in this example updating an image's src with a data attribute's value):
$(document).ready(function() {
var $img = $('#items-content [data-imgslap]');
var newSrc = $img.data('imgslap');
$img.attr('src', 'http://i.imgur.com/' + newSrc + '.jpg"');
} );
jsfiddle: https://jsfiddle.net/patrickberkeley/bx686410/2/
Regex to replace img src in a string
Based on the comments you've left though, it seems like your goal is to a value in a string (rather than updating an img element's src in the DOM).
In order to do that:
var str = '<div id="items-content"><p><img class="fr-dib" src="http://i.imgur.com/bEDR9dc.png" data-imgslap="mJyABlG" style="width: 214px;"></p></div>';
var newSrc = 'http://i.imgur.com/mJyABlG.png';
var newStr = str.replace(/<img(.*)src=[\"|\'](.*?)[\"|\'](.*)/, "<img$1src='" + newSrc + "'$3");
jsfiddle: https://jsfiddle.net/patrickberkeley/qrdt1esz/1/
Notice you *do not $(document).ready() because you're not selecting something from the dom. The above regex should handle: single and double quotes and any combination of attrs on either side of the img's src.

Insert an IMG tag into the DOM using JavaScript and anchor tag

At the moment I have the following JavaScript function that inserts an IMG tag into the DOM:
function createHeaderImageRight() {
var parentElement = $("#sidebar");
var img1 = $('<img />', {
id: 'headerImageLeft',
src: '/Images/Header/FGM2.jpg',
"class": 'img-responsive headerImageLeft',
alt: ''
});
img1.appendTo(parentElement);
}
I'd like to modify this to also include an anchor tag so that when the image is clicked, we can take the user to a URL. I'm not sure how to modify this code to include the tag I need.
why cant you do like this..
$("#sidebar").append('<img id="headerImageLeft" src="/Images/Header/FGM2.jpg" class="img-responsive headerImageLeft"/>');
You could use the same technique that you used for your img tag.
var a1 = $('<a />',
{ id: 'headerImageLeftLink',
href: 'http://somewebsite.com'
});
img1.appendTo(a1);
a1.appendTo(parentElement);
Or, you could chain the appends like so:
parentElement.append(a1).append(img1);

Alternative writing method to create DOM elements and append

If I want to append a button with my pic to the document, I would write:
$('#story_pages').append('<div><button value="'+window_value+'" onclick="reload_to_canvas(this.value)" > <img id= "w'+window_value+'", src="../pic/white_img.png", width="110px", height="110px"/> </button></div>');
It's too long and hard to debug. But how can I create an img tag, then wrapping it with a button tag and div tag...
Please suggest any clear and simple method with jQuery's help.
UPDATE:
story_pages is the jQuery UI dialog's id. I don't know if it affects or not.
UPDATE:
I found the problem. I want the image shown above on the button instead of a button and a image.
The script you give me will result this:
<div>
<button value="1"></button>
<img ......./>
</div>
The img tag has to be wrapped by button tag like:
<button>
<img.../>
</button>
So the image will attach on the button.
How about this:
var $button = $('<button>', {
value: window_value,
click: function() { reload_to_canvas(this.value); }
});
var $img = $('<img>', {
id : 'w'+ window_value,
src: '../pic/white_img.png'
})
.css({ height: '100px', width: '100px'});
$('#story_pages').append($('<div>').append($button, $img));
If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with ). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements.
try this
var div=$('<div>'); // creates new div element
//updated here
var img = $('<img />') .attr({ // create new img elementand adds the mentioned attr
id:'w'+window_value ,
src:"../pic/white_img.png",
width:"110px",
height:"110px"});
var button= $('<button/>', //creates new button
{
value: window_value, //add text to button
click: function(){ reload_to_canvas(this.value)} //and the click event
}).html(img); /// and <-- here... pushed the created img to buttons html
div.append(button); //append button ,img to div
$('#story_pages').append(div); //finally appends div to the selector
updated example fiddle
$('#story_pages').append(
$('<div>').append(
$('<button>', {
value : window_value
}).click(function() {
reload_to_canvas(this.value);
}).append(
$('<img>', {
id : 'w' + window_value,
src : '../pic/white_img.png'
}).width(110)
.height(110)
)
)
);

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

I understand JQuery in the basic sense but am definitely new to it, and suspect this is very easy.
I've got my image src and id in a JSON response (converted to an object), and therefore the correct values in responseObject.imgurl and responseObject.imgid, and now I'd like to create an image with it and append it to a div (lets call it <div id="imagediv">. I'm a bit stuck on dynamically building the <img src="dynamic" id="dynamic"> - most of the examples I've seen involve replacing the src on an existing image, but I don't have an existing image.
In jQuery, a new element can be created by passing a HTML string to the constructor, as shown below:
var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
img.attr('src', responseObject.imgurl);
img.appendTo('#imagediv');
var img = $('<img />', {
id: 'Myid',
src: 'MySrc.gif',
alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));
You save some bytes by avoiding the .attr altogether by passing the properties to the jQuery constructor:
var img = $('<img />',
{ id: 'Myid',
src: 'MySrc.gif',
width: 300
})
.appendTo($('#YourDiv'));
For those who need the same feature in IE 8, this is how I solved the problem:
var myImage = $('<img/>');
myImage.attr('width', 300);
myImage.attr('height', 300);
myImage.attr('class', "groupMediaPhoto");
myImage.attr('src', photoUrl);
I could not force IE8 to use object in constructor.

Append element2 to element1 before appending element1 to document

I'm looking to create an element dynamically with jQuery and put another element dynamically within that, but before I append it.
For example, I want the output to look like so:
<span class="imageContainer">
<p>Close</p>
<img src="image.jpg" />
<span>
I could use the following, but it prevents me from using the other method of supplying the attributes:
$('<span class="imageContainer"><p>Close</p><img src="image.jpg" /></span>').prependTo('body');
I'm currently creating the span element with this code, and would like to know how I can append code to it before I append it to anything, this is probably a simple solution that I'm just overlooking:
$('<span/>', {
'id': 'imageContainer'
});
The reason I want to use this method, is so I can attach click methods and such in one go.
UPDATED SOLUTION (thanks to #ParvSharma):
function hoverBox( url, e ) {
var hoverbox = $( '<span/>', {
'id': 'imageContainer',
'style': 'top:'+e.pageY+'px; left:'+e.pageX+'px;'
}).append(
$('<p/>', {
html: 'Close',
click: function() {
var parentContainer = '#'+$(this).parent().attr('id');
destroy( parentContainer );
}
})
).append(
$('<img/>', {
'src': url
})
);
return hoverbox;
}
make the span
var span = $('<span/>', { 'id': 'imageContainer'});
then just do
span.append($("<p></p>"));
then jo
span.append($("<img></img>"));
now append span to anything u want to append it to
Try this:
$('<span class="imageContainer"><p>Close</p><img src="image.jpg" /></span>')
.find('p')
.click(function() {
// click code here.
})
.end()
.prependTo('body');
Try this
$('<span class="imageContainer"><p>Close</p><img src="image.jpg" /></span>').find("img").attr({}).end().prependTo('body');
You can also use this based on your requirement.
$('<span/>', {
'id': 'imageContainer'
}).append('<p>Close</p><img src="image.jpg" />')
.prependTo('body');
$('<span/>', {'id':'theId'}).click(....);
Once you create an element with jQuery it returns jQuery object of it...

Categories