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...
Related
If I have a structure like this:
var myThing = jQuery(
jQuery('<div/>')
.addClass('myTopDiv')
.append(
jQuery('<div/>')
.text('some text')
.addClass('mySecondDiv')
).append('<div/>')
.text('some more text') // I WANT TO REPLACE THIS TEXT
);
How do I target the div which contains the text some more text and replace that text with new text?
I've stored it inside a variable called myThing, but I don't know how to navigate down to the div I want.
I can't use the classes as selectors as there are multiple instances of this variable in my application.
Something like this perhaps? Which doesn't work...
jQuery(
jQuery('<tr/>')
.text('new text')
).appendTo(myThing);
You stop the crazy nesting, and use variables
var topDiv = $('<div />', {
'class' : 'myTopDiv'
}),
secDiv = $('<div />', {
'class' : 'mySecondDiv',
text : 'some text'
}),
thrDiv = $('<div />', {
text : 'some more text'
});
topDiv.append(secDiv, thrDiv);
// change text
thrDiv.text('Some other text');
Not sure but maybe:
jQuery('div.myTopDiv div:last').text()
?
Try this one,
$( "div:contains('John')" )
According to Jquery Documentation it will select the div by it's content
Hope this helps.
You have an error in your code (probably because of complex nesting). check this fiddle http://jsfiddle.net/r1h8fy9j/ for corrected one and two possible solutions for your issue:
jQuery(myThing).find('div:last').text('text to replace to'); - in case if target div is the last one.
jQuery(myThing).find('div').eq(1).text('text to replace to'); - in case if target div is at specific index.
I am creating a jQuery div element as below;
var divEle = $('<div />', {'class': 'editableTxt','data-model-attr':currElmModelAttr,'data-model-id':'currElmModelId'});
Now I want to append html text/value inside this div...
So it should render as;
<div class="editableTxt" data-model-attr="modelAttr" data-model-id="currElmModelId">My INNER HTML/TEXT</div>
I am currently doing;
$(this).parent().append(divEle).append($(this).val());
But this renders it as separate child element and not inside the divEle...
How do I specify in the same syntax above ?
You should use .html() to set html to divEle
$(this).parent().append(divEle.html($(this).val()));
OR
Simply use
var divEle = $('<div />', {
'class': 'editableTxt',
'data-model-attr': currElmModelAttr,
'data-model-id': 'currElmModelId',
'html' : 'My INNER HTML/TEXT'
});
DEMO
you can try this..
place this after inserting the div..
$('.editableTxt').html('my text here');
Try this :
$(this).parent().append($(divEle).html($(this).val()));
Working JSfiddle
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 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');
});
My div structure should be this:
<div id="dashboard">
<img id="pic1" src="...png" />
<h6>....</h6>
</div>
To create the div I use this:
$('<div>', {
'id': 'dashboard'
}).appendTo('body');
I need to append a h6 tag with text into the above div. How can this be done? Also how can I access the text within the h6 tag when the div is clicked?
$('#dashboard div').hover(function() {
alert($(this).children().eq(2) ?? );
};
To add the h6 element, try this:
var $div = $('<div>', {
'id':'dashboard'
}).appendTo('body');
$("<h6></h6>").text("Foo").appendTo($div);
To access the text of the h6 on click of the div, try this:
$("body").delegate("#dashboard", "click", function() {
var text = $("h6", this).text();
alert(text);
});
That assumes you are using jQuery 1.6 or lower. If you are using jQuery 1.7+, you can use on():
$("body").on("click", "#dashboard", function() {
var text = $("h6", this).text();
alert(text);
});
Example fiddle
Also, I have used $("body") here as an example - you should use a selector which is the closest to the element you are attaching the event to (in this case #dashboard) which is not dynamically created.