jQuery specify inner html - javascript

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

Related

Jquery add data to html before adding to DOM

I am building html on the fly need to add data before I add it to DOM. Since I am looping thru' lot of information, I would like to add the relevant data info along with the dom I am building instead of adding the html and then looping thru again to add the data.
result.forEach(function(record) {
html += '<div id ="' record.ID + '">test content </div> ';
//add data to above
});
I can do another loop here after adding it to DOM
$(body).append(html);
testresult.forEach(function(record) {
$("#" +record.ID).data(record);
});
Instead of concatenating strings to piece together your HTML, you may way to try something like this:
result.forEach(function(record) {
$('.selector').append(function () {
var $div = $('<div></div>');
$div.attr('id', record.testID).text('some text');
return $div;
});
});
This creates a new div jquery object for each item in result. You can use the record object to add attributes, data, text, etc to you object. It will be added the DOM when the callback passed into .append returns your new jquery DOM object.
Start trying to use jQuery to create your html elements so you can take fully advantage of jQuery and its plugins.
Ex:
var div = $("<div></div>") // create the element
.text("test content") // change the inner text
.attr("id", record.testID); // set the element id
div.appendTo("body");
You can check out [http://www.w3schools.com/jquery/] as a great source for learning jQuery.
You have quotes problem in the following line :
html += '<div id =record.testID' + '>test content </div> ';
________^______________________^___^_____________________^
You should fix that using double quotes because as it's now the string will be considered as '<div id =record.testID'.
html += '<div id="'+record.testID+'">test content </div>';
Or you could use separated definition :
$.each(result, function(index,record) {
var div = $('<div>test content</div>');
div.attr('id', record.testID);
div.data('test', record.testDATA);
$('body').append(div);
})
Hope this helps.
var result = [{testID: 1,testDATA: 'data 1'},{testID: 2,testDATA: 'data 2'},{testID: 3,testDATA: 'data 3'}]
var html='';
$.each(result, function(index,record) {
var div = $('<div>test content</div>');
div.attr('id', record.testID);
div.data('test', record.testDATA);
console.log(div.data('test'));
$('body').append(div);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

What selector do I use to access this div?

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.

Replace the text using javascript

Im using the below code to replace the text within the h1 tag, but its not getting effected. I want to replace "sample" to "new sample". I'm doing wrong?
<div class="content">
<h2>sample</h2>
</div>
var t = jQuery('.content');
t.children("h2").each(function() {
var contents = jQuery(this).contents();
jQuery(this).replaceWith(new sample);
});
use .html() to set html.try this:
$('.content h2').html('new sample');
Working Demo
If you want to replace some part of content then try this:
jQuery('.content h2').each(function(i, v) {
$v = $(v);
$v.html($v.html().replace('sample', 'new sample'));
});
jsFiddle
Use jQuery's .text()
$(".content h2").text("new sample");
FIDDLE
You can do that without jQuery:
var elem = document.getElementsByTagName('h2')[0];
elem.innerHTML = "New Value";
Set .text()
t.children("h2").text('new sample'));
If you want to set .html() content
t.children("h2").html('new sample'));
Child Selector (“parent > child”)
$('.content > h2').html('new sample');

take on height on element to be replaced

I'm replacing elements that match a class with .replaceWith() as used here: $('.dataCard').not('.focused').replaceWith('<div class="spaceHolder"></div>');;however, I want each of the .spaceHolders to take on the heights of the .dataCards they replace before they replace them.
How can I do that?
$('.dataCard').not('.focused').each(function() {
var div = $('<div />', {
css : {height : $(this).height()}
});
$(this).replaceWith(div);
});

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)
)
)
);

Categories