I have this variable called $reservas that contains a string with HTML Tables. I want to remove parts of the tables (.tdRemove), BEFORE I assign them to the div #cenas.
if ($reservas){
$($reservas).find('.tdRemove').each(function(){
console.log($(this).html());
$(this).remove();
});
$("#cenas").html($reservas);
}
I tried this, but it doesn't seem to remove anything.
I've also tried:
$($reservas).find('.tdRemove').remove(); and $($reservas).remove('.tdRemove');
Nothing works. Any suggestions?
Is there any way to tell jQuery that the variable holds html content, and should be parsed as that? If so, how? ..
After converting your string to a jQuery object, it is now a series of DOM objects (in a document fragment) held in the jQuery object. After removing the .tdRemove objects in that fragment, you can then just append that directly to your DOM. No need to go back to HTML:
if ($reservas){
var item = $($reservas);
item.find('.tdRemove').remove();
$("#cenas").empty().append(item);
}
Also, your code didn't work because the $reservas string of HTML was never modified.
I think, from what the documentation tells me, you can only remove() what is already inside the DOM.
Remove the set of matched elements from the DOM.
Maybe you want to add your table first, set it to ? display: none`, then filter for elements to remove and finally display the table.
if ($reservas) {
$("#cenas")
.hide()
.html($reservas)
.find('.tdRemove').each(function(){
console.log($(this).html());
$(this).remove();
})
.show();
}
Related
I want to clear all list items in my <body>. So on a button press, the item text from all the lists are removed. No use of IDs or anything, just if there is an <li> tag, it's innerHTML is cleared out.
I have tried a few different methods, but I cannot figure it out.
Any help is appreciated.
Basically what I was trying to do is clearly incorrect as you can see here:
function clearLI() {
document.getElementById("li").innerHTML = ""
};
You can do this quite simply by iterating over every li element and settings its innerHTML to nil.
Here's the code.
Array.from(document.getElementsByTagName('li')).forEach(el => el.innerHTML = '');
You mean
innerHTML.replace(newValue);
?
Or did you forget to hyperlink Li to body?
I'm new to jQuery and am trying to create jQuery UI buttons dynamically and them to a list. I can create one list item but no more are appended after it. What am I doing wrong?
$('#buttonList').append('<li><button>'+ username + '</button>')
.button()
.data('type', userType)
.click(function(e) { alert($(this).data('type')); })
.append('<button>Edit</button></li>');
<div>
<ul id="buttonList">
</ul>
</div>
This only creates one list item with two buttons (although the second button seems to be encased in the first one, but I can probably figure that issue out). How do I get it to create multiple list items with their own unique 'data' values (i.e. I can't do a find() on a particular button class and give it data values as all buttons would then have the same data)?
I suggest to exchange the position of what you are appending and where you are appending to. This way, you retain the appended object, and should be able to work with it as a standard jQuery selector. From your code i commented out the .button() and the .append() lines, because i'm not sure what you want to do with them. Should you need help adding those lines, just drop a comment to my answer ;)
Oh, i almost forgot: i use var i to simulate different contents for username and userType data.
A JSFiddle for you is here: http://jsfiddle.net/cRjh9/1/
Example code (html part):
<div>
<p id="addButton">add button</p>
<ul id="buttonList">
</ul>
</div>
Example code (js part):
var i = 0;
$('#addButton').on('click', function()
{
$('<li><button class="itemButton">'+ 'username' + i + '</button></li>').appendTo('#buttonList')
//.button()
.find('.itemButton')
.data('type', 'userType'+i)
.click(function(e) { alert($(this).data('type'));
})
//.append('<button>Edit</button></li>')
;
i++;
});
You need complete tags when you wrap any html in a method argument. You can't treat the DOM like a text editor and append a start tag, append some more tags and then append the end tag.
Anything insterted into the DOM has to be complete and valid html.
You are also not understanding the context of what is returned from append(). It is not the element(s) within the arguments it is the element collection you are appending to. You are calling button() on the whole <UL>.
I suggest you get a better understanding of jQuery before trying to chain so many methods together
Just a very simplistic approach that you can modify - FIDDLE.
I haven't added the data attributes, nor the click function (I'm not really sure I like the
inline "click" functions - I generally do them in jQuery and try to figure out how to make
the code efficient. Probably not very rational, but I'm often so).
JS
var names = ['Washington', 'Adams', 'Jefferson', 'Lincoln', 'Roosevelt'];
for( r=0; r < names.length; r++ )
{
$('#buttonList').append('<li><button>'+ names[r] + '</button></li>');
}
$('#buttonList').append('<li><button>Edit</button></li>');
I am building a block of nested divs around a specific element on the client. I am using jQuery's .wrap() initially to get the first part of the block which is working fine. But now I want to attach the ending block after the element I am wrapping and I am finding I can't attach it to anything because it is all being created at the same time. I tried using insertAfter() but I don't want it to be a sibling of the element I am wrapping, I want it to come after it's parent.
Here is my code:
$(document).ready(function() {
buildShadows('#section');
});
function buildShadows(element){
$(element).wrap("<div class='section_shadow_wrapper'><div class='section_shadow_curve'><div class='section_shadow_outer'><div class='section_shadow_inner_left'><div class='section_shadow_inner_right'>");
$("<div class='section_shadow_bottom_left'><div class='section_test_bottom_right'>").insertAfter(element);
}
What I am trying to do is append the first element of the second part (section_shadow_bottom_left) as a sibling of 'section_shadow_inner_right' but after 'element'
Any help would be appreciated.
Thanks.
You should be able to just traverse up to the new parent you just created.
Have you tried this?
function buildShadows(element){
$(element).wrap('<div class="section_shadow_wrapper clearfix"><div class="section_shadow_curve"><div class="section_shadow_outer"><div class="section_shadow_inner_left"><div class="section_shadow_inner_right">')
.parent().after('<div class="section_shadow_bottom_left"><div class="section_test_bottom_right">');
}
Try traversing to the next sibling of the original element and using .insertBefore() on it.
var nextsibling = $(element).next();
//Wrap code
$("<div class='section_shadow_bottom_left'><div class='section_test_bottom_right'>").insertBefore(nextsibling);
Perhaps I'm using $.data incorrectly.
Assigning the data:
var course_li = sprintf('<li class="draggable course">%s</li>', course["fields"]["name"]);
$(course_li).data('pk', course['pk']);
alert(course['pk']); // shows a correct value
alert($(course_li).data('pk')); // shows null. curious...
course_li is later appended to the DOM.
Moving the li to a different ul:
function moveToTerm(item, term) {
item.fadeOut(function() {
item.appendTo(term).fadeIn();
});
}
Trying to access the data later:
$.each($(term).children(".course"), function(index, course) {
var pk = $(course).data('pk');
// pk is undefined
courses.push(pk);
});
What am I doing wrong? I have confirmed that the course li on which I am setting the data is the same as the one on which I am looking for it. (Unless I'm messing that up by calling appendTo() on it?)
When you store the data:
$(course_li).data('pk', course['pk']);
you're creating an element but not saving it, so it's lost. Your alert test test the wrong value; it should be:
$(course_li).data('pk', course['pk']);
alert($(course_li).data('pk'));
which is null. Consider:
$(course_li);
$(course_li);
This creates two different elements with source equal to course_li, which are then promptly lost. What you need to do is create the element first, then work with that single element (i.e. don't call $(course_li) more than once). For example,
var course_li = $(sprintf('<li class="draggable course">%s</li>',
course["fields"]["name"]));
course_li.data('pk', course['pk']);
parent.append(course_li);
Note that course_li now holds an element, rather than a string.
try checking to see if the element being created by this call:
$(course_li)
is a single 'li' element, or a div. From the doco:
When the HTML is more complex than a single tag without attributes, as it is in the above example... snip ...Specifically, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in
So it's probably creating a div that you are assigning the data to, so when you select the 'li' itself, you are getting a child of the actual element that you set the data on.
I have a div <div id="masterdiv"> which has several child <div>s.
Example:
<div id="masterdiv">
<div id="childdiv1" />
<div id="childdiv2" />
<div id="childdiv3" />
</div>
How to clear the contents of all child <div>s inside the master <div> using jQuery?
jQuery's empty() function does just that:
$('#masterdiv').empty();
clears the master div.
$('#masterdiv div').empty();
clears all the child divs, but leaves the master intact.
jQuery('#masterdiv div').html('');
Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.
$('#masterdiv div').empty();
Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.
I know this is a jQuery related question, but I believe someone might get here expecting a pure Javascript solution. So, if you were trying to do this using js, you could use the innerHTML property and set it to an empty string.
document.getElementById('masterdiv').innerHTML = '';
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
The better way is :
$( ".masterdiv" ).empty();
$("#masterdiv div").text("");
$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")
$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div
You can use .empty() function to clear all the child elements
$(document).ready(function () {
$("#button").click(function () {
//only the content inside of the element will be deleted
$("#masterdiv").empty();
});
});
To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/
When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();
$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});
or
$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});
try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();