What selector do I use to access this div? - javascript

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.

Related

Adding selectors into dynamically generated <li > element

I am trying to dynamically generate html content. However it seem like whenever I add tags or selectors to the li element, the code malfunctions
Correct behavior
Incorrect behavior
$('#btnName').click(function(){
var text = $('#inputName').val() + '<button>x</button>';
if(text.length){
$('<li name="somename" id="someid"/>', {html: text}).appendTo('ul.justList') // adding name tag and id selector cause error
}
});
$('ul').on('click','button' , function(el){
$(this).parent().remove()
});
Demo
Use the second parameter to set the other attributes rather than write them out in the tag. Also, you don't need to self-close the tag.
$('#btnName').click(function(){
var text = $('#inputName').val() + '<button>x</button>';
if(text.length){
$('<li>', {
html: text,
name: 'somename',
id: 'someid' + $('.justList li').length // for the sake of unique ids in the example
}).appendTo('ul.justList')
}
});

jQuery specify inner html

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

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

How to change text inside span with jQuery, leaving other span contained nodes intact?

I have the following HTML snippet:
<span class="target">Change me <a class="changeme" href="#">now</a></span>
I'd like to change the text node (i.e. "Change me ") inside the span from jQuery, while leaving the nested <a> tag with all attributes etc. intact. My initial huch was to use .text(...) on the span node, but as it turns out this will replace the whole inner part with the passed textual content.
I solved this with first cloning the <a> tag, then setting the new text content of <span> (which will remove the original <a> tag), and finally appending the cloned <a> tag to my <span>. This works, but feels such an overkill for a simple task like this. Btw. I can't guarantee that there will be an initial text node inside the span - it might be empty, just like:
<span class="target"><a class="changeme" href="#">now</a></span>
I did a jsfiddle too. So, what would be the neat way to do this?
Try something like:
$('a.changeme').on('click', function() {
$(this).closest('.target').contents().not(this).eq(0).replaceWith('Do it again ');
});
demo: http://jsfiddle.net/eEMGz/
ref: http://api.jquery.com/contents/
Update:
I guess I read your question wrong, and you're trying to replace the text if it's already there and inject it otherwise. For this, try:
$('a.changeme').on('click', function() {
var
$tmp = $(this).closest('.target').contents().not(this).eq(0),
dia = document.createTextNode('Do it again ');
$tmp.length > 0 ? $tmp.replaceWith(dia) : $(dia).insertBefore(this);
});
​Demo: http://jsfiddle.net/eEMGz/3/
You can use .contents():
//set the new text to replace the old text
var newText = 'New Text';
//bind `click` event handler to the `.changeme` elements
$('.changeme').on('click', function () {
//iterate over the nodes in this `<span>` element
$.each($(this).parent().contents(), function () {
//if the type of this node is undefined then it's a text node and we want to replace it
if (typeof this.tagName == 'undefined') {
//to replace the node we can use `.replaceWith()`
$(this).replaceWith(newText);
}
});
});​
Here is a demo: http://jsfiddle.net/jasper/PURHA/1/
Some docs for ya:
.contents(): http://api.jquery.com/contents
.replaceWith(): http://api.jquery.com/replacewith
typeof: https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof
Update
var newText = 'New Text';
$('a').on('click', function () {
$.each($(this).parent().contents(), function () {
if (typeof this.tagName == 'undefined') {
//instead of replacing this node with the replacement string, just replace it with a blank string
$(this).replaceWith('');
}
});
//then add the replacement string to the `<span>` element regardless of it's initial state
$(this).parent().prepend(newText);
});​
Demo: http://jsfiddle.net/jasper/PURHA/2/
You can try this.
var $textNode, $parent;
$('.changeme').on('click', function(){
$parent = $(this).parent();
$textNode= $parent.contents().filter(function() {
return this.nodeType == 3;
});
if($textNode.length){
$textNode.replaceWith('Content changed')
}
else{
$parent.prepend('New content');
}
});
Working demo - http://jsfiddle.net/ShankarSangoli/yx5Ju/8/
You step out of jQuery because it doesn't help you to deal with text nodes. The following will remove the first child of every <span> element with class "target" if and only if it exists and is a text node.
Demo: http://jsfiddle.net/yx5Ju/11/
Code:
$('span.target').each(function() {
var firstChild = this.firstChild;
if (firstChild && firstChild.nodeType == 3) {
firstChild.data = "Do it again";
}
});
This is not a perfect example I guess, but you could use contents function.
console.log($("span.target").contents()[0].data);
You could wrap the text into a span ... but ...
try this.
http://jsfiddle.net/Y8tMk/
$(function(){
var txt = '';
$('.target').contents().each(function(){
if(this.nodeType==3){
this.textContent = 'done ';
}
});
});
You can change the native (non-jquery) data property of the object. Updated jsfiddle here: http://jsfiddle.net/elgreg/yx5Ju/2/
Something like:
$('a.changeme3').click(function(){
$('span.target3').contents().get(0).data = 'Do it again';
});
The contents() gets the innards and the get(0) gets us back to the original element and the .data is now a reference to the native js textnode. (I haven't tested this cross browser.)
This jsfiddle and answer are really just an expanded explanation of the answer to this question:
Change text-nodes text
$('a.changeme').click(function() {
var firstNode= $(this).parent().contents()[0];
if( firstNode.nodeType==3){
firstNode.nodeValue='New text';
}
})
EDIT: not sure what layout rules you need, update to test only first node, otherwise adapt as needed

Categories