I have the following script which is working nicely to hide a DIV when its child is empty:
jQuery(".field-items").filter(function() {
return !$.trim(this.innerHTML);
}).parent().parent().parent().parent().parent().parent().hide();
If that same DIV is empty from above I also want to hide another DIV on the same page. It's not a parent.
How can I add the following code to the above code? So that both occur when that specific DIV is empty?
$('#survey-monkey-title').hide();
var $empty = jQuery(".field-items").filter(function() {
return !$.trim(this.innerHTML);
});
if ($empty.length) {
$empty.parent().parent().parent().parent().parent().parent().hide();
$('#survey-monkey-title').hide();
}
I'd also like to give Brian Giaz his propers for utilizing .add() below:
$empty.parent().parent().parent().parent().parent().parent().add('#survey-monkey-title').hide();
You can use the add() function to add additional elements to the jquery object:
$('#elem').parent().add('#otherElem').hide();
for example.
I know you already got it working, but consider updating the stringed parent() calls to just a single parentUntil function.
var $empty = jQuery(".field-items").filter(function() {
return !$.trim(this.innerHTML);
});
if ($empty.length) {
$empty.parentsUntil('.someSelector').hide();
$('#survey-monkey-title').hide();
}
Related
I want to insert a label called "octosplit-label" right under the current octosplit-label.
How do I do this in Javascript?
I had an attempt that didn't work here
function addOneCheckbox($label) {
$('#issues-container .table-list').append($label);
}
Try modifying your function like this:
function addOneCheckbox($label) {
$('#octosplit-label').after($label);
}
Remember that IDs should be unique, so the HTML contained within $label should not have the same ID (which is octosplit-label) and also there should be no other labels currently on the page with that same ID.
This should work for you (from jQuery documents:
function addOneCheckbox($label) {
$($label).insertAfter('#octosplit-label');
}
The $label needs to be all of the html for the label.
Please keep in mind that IDs have to be unique; therefore you cannot give the new label the same ID as the existing one:
$('#octosplit-label').after( $('<label/>',{'id':'some_id','for':'if_so_desired'}) );
Reference:
jQuery.after() API Documentation
You should add some validation before try to modifying the DOM.
function addOneCheckbox(label) {
var element = $('#issuelist').find('#octosplit-label');
if(element.length > 0) {
element.append(label);
}
}
how to store data received from below Jquery for further use.
$('#div').find('a').each(function() {
console.log($(this).attr('href'));
});
http://jsfiddle.net/mvm6o208/ you can find my code here.
Make an array and push values to it. Like
var store = [];
$('#div').find('a').each(function() {
store.push($(this).attr('href'));
});
Update : According to the html in the fiddle you have posted, the selector should be $('div').find('a') instead of $('#div').find('a'), as you dont have any div with id div. See a working fiddle here.
Also as per the inputs from comments below, it would be faster approach to push to an array via
store[store.length] = $(this).attr('href');
var refsArray = $('#div').find('a').map(function(item) {
return $(item).attr('href');
});
You are targeting a div and not a thing like this id="div", so you just need to remove the # :
$('div').find('a').each(function() {
console.log($(this).attr('href'));
});
I've been searching for a few hours to try and find a solution to my issue, for some reason partially similar answers on here don't seem to be working for me - so I'm creating my own question.
Basically, I'm loading pre-rendered HTML from the server using jQuery's $.get method, and I need to split the HTML returned into two sections (one that's wrapped in a div called #section-one and the other simply alongside that div, with no parent element).
See the example below:
$.get('http://jamie.st/remote_file.php', function(data){
// I want to get '#section-one' and then remove it from data, basically splitting a single returned HTML resource into two, that can be placed in two different areas of the page.
var sectionOne = $(data).find('#section-one');
// This should only return the HTML of '#section-one'
console.log(sectionOne);
// Also how can I then remove '#section-one' from the 'data' variable? The equivalent of calling the below, but from the 'data' variables string/html.
$(sectionOne).remove();
// So eventually the below would return the HTML without the '#section-one' element (and it's children)
console.log(data);
});
I've also created a jsfiddle which you can play around with if you need to, it's set up to use a real PHP file that I've hosted for demo purposes.
http://jsfiddle.net/6p0spp23/6/
If you can submit a jsfiddle link back that would be much appreciated, thanks in advance guys!
When you create a jQuery object with the remote contents $(data) becomes a collection of elements so instead of find() you want to use filter() like so:
$.get('http://jamie.st/remote_file.php', function(data){
var $data = $(data),
$sectionOne = $data.filter('#section-one'),
$rest = $data.filter(':not(#section-one)');
console.log($sectionOne);
console.log($rest);
});
Demo fiddle
I think the best way to put the received data inside a parent div. Then you can call remove or any other method to use it.
You can make parent div hidden using .hide() method if you don't want to show it.
Here I did it:
http://plnkr.co/edit/jQKXyles8sP8dliB7v0K?p=preview
// Add your javascript here
$(function() {
$.get('http://jamie.st/remote_file.php', function(data) {
$("#parent").hide();
$("#parent").html(data);
$("#section-one").remove();
console.log($("#section-one").html())
alert($("#parent").html())
});
});
When you remove a subsection from a derived jQuery object, the original string is not updated with the change so if you want the updated html content you need to generate it from the jQuery object. One way to do this is to
$.get('http://jamie.st/remote_file.php', function (data) {
var $ct = $('<div />', {
html: data
});
// I want to get '#section-one' and then remove it from data, basically splitting a single returned HTML resource into two, that can be placed in two different areas of the page.
var sectionOne = $ct.find('#section-one');
// This should only return the HTML of '#section-one'
console.log(sectionOne);
// Also how can I then remove '#section-one' from the 'data' variable? The equivilant of calling the below, but from the 'data' variables string/html.
$(sectionOne).remove();
// So eventually the below would return the HTML without the '#section-one' element (and it's children)
console.log($ct.html());
});
Demo: Fiddle
I'm new to jQuery and I can get it to sometimes work, however, for some reason, when I try to call a function, it gives me the title error, but if I do it in developer tools, it works fine.
http://jsfiddle.net/otanan/pmzzLo3e/#&togetherjs=AezijhfBrj
It seems to work fine when retrieving the classes from the DOM, but not when I call a function such as
.click(function() {});
Here's the code:
var downloads = $(".info"),
className = "info_clicked";
for(var i in downloads)
{
downloads[i].click(function()
{
if(!this.hasClass(className))
this.addClass(className);
else
this.removeClass(className);
});
}
When you access a jQuery collection as an array, it returns the DOM elements, not jQuery objects. You should use .each() rather than for (i in downloads):
downloads.each(function() {
$(this).click(function() {
if (!$(this).hasClass(className)) {
$(this).addClass(className);
} else {
$(this).removeClass(className);
}
});
});
You could also simplify the whole thing to:
downloads.click(function() {
$(this).toggleClass(className);
});
Most jQuery methods automatically iterate over all the elements in a collection if it makes sense to do so (the notable exceptions are methods that return information from the element, like .text() or .val() -- they just use the first element). So you generally only have to iterate explicitly if you need to do different things for each element. This is one of the great conveniences of using jQuery rather than plain JS: you rarely have to write explicit iterations.
I think the issue is that you're attempting to call a jQuery function on an object that is no longer a jQuery object.
For example you're saying $(".info"). Which retrieves a single jQuery object. As soon as you index that object downloads[i] it is no longer a jQuery object, it is a plain HTML element and does not have a click function available.
What you really need to do is get the jQuery object for the indexed item:
var downloads = $(".info"),
className = "info_clicked";
for(var i = 0; i < downloads.length; i++)
{
$(downloads[i]).click(function()
{
if(!this.hasClass(className))
this.addClass(className);
else
this.removeClass(className);
});
}
try it:
$(downloads[i]).click(function(){ //...
I'm using a modular pattern for writing my JS code. I have an object with references to all my dom elements. I have put the selector for a div that I'm adding at a later point in my code execution. When I add that div, and use jQuery.css using the reference I stored in my references object, it doesn't work.
NameSpace = {
objects: {
someButton: $('.someButton'),
someDiv: $('.someDiv'),
myDiv: $('.myDiv'), //This will be added later
//Other references
.
.
},
bindHandlers: {
NameSpace.objects.someButton.on('click', someEventHandler);
//Other bindings
.
.
},
eventHandlers: {
someEventHandler: function(e){
var div = jQuery('<div class="myDiv"></div>');
NameSpace.objects.someDiv.append(div);
//Doesn't work! If I use jQuery('.myDiv'), then it works,
//but kills my modular style
NameSpace.objects.myDiv.css({ //some styles });
},
//Other event handlers
}
}
//Other code
This approach works fine for objects that exist in the page, but isn't working for a div that I add like above.
Any help?
Javascript is procedural, this line myDiv: $('.myDiv') is computed only once and not everytime you call it.
It means that your selector $('.myDiv') is filled at the start of your page.
To resolve this you'd have to make your variable a function
objects: {
someButton: $('.someButton'),
someDiv: $('.someDiv'),
myDiv: function(){ return $('.myDiv'); }, //This will be added later
//Other references
.
.
},
It should recalculate the selector everytime you call it.
Let me know if the trick works.