jQuery combine multiple elements - javascript

I was experimenting with jQuery and came across a question. Can I use an actual selector with existing element as a combined selector for jQuery?
So, suppose I've created a DIV element on-the-fly:
var $div = $('<div>')
.css('position', 'absolute')
.hide(); // Just to be short
$('body').append($div);
And I want to show it when user hovers over P elements / paragraphs (at the cursor position):
$('p').hover(function(e) {
// Change the position of $div with regards of cursor position
$div.show();
}, function(e) {
$div.hide();
});
BUT also I want to apply this hover handlers to $div itself. So instead of duplicating my code, I want to do something like this:
$('p', $div).hover(...)
which will select $div element along with all P elements.
I know I can write functions separately and pass the names as arguments to hover function.
Is there any solution to this kind of situation in jQuery? or is there a more accurate solution?

You could use the jQuery add method:
$('p').add($div).hover(function(e) { ...

If you have multiple elements to combine you don't wan to do
$('p').add($div1).add($div2).add($div3).add($div4).add($div5).add($div6) ...
Instead you want to convert a JavaScript array into a jQuery object
$( $.map([x,y,z], a => [...$.makeArray(a)]) )
Source: Merging jQuery objects

Related

How do you target an element that is dynamically generated? [duplicate]

Beginner to all of this, playing around with Firebase. Basically, I want to retrieve text entries from Firebase and have an "Approve" button next to it. When the button is clicked, I want that specific text entry to be pushed to a new Firebase location and the text removed from the page. I am creating the button and the text dynamically and I am having some trouble with selecting the button and the divs I created. I know I have to use on() but I'm unsure of how to use it.
Thanks!
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
$('<div id="post">').text(posts.text).append('<button style ="button" id="approve">Approve</button>').appendTo($('#feed'));
});
$('#approve').on("click", function(){
var text = $('#post').val();
postsRef.push({'text':text});
$('#post').remove();
});
You have to bind .on() on a container of your dynamically added element that is already on the page when you load it, and have it like this:
$('#yourContainer').on('click', '#approve', function(){
//your code here..
});
Your .on() didn't work, because you are adding the button dynamically. You can't find the dynamically added elements directly using that elements id selector like $('#approve'). So you should
bind .on() with $(document) selector. This will always contain your dynamically added elements.
$(document).on( eventName, selector, function(){} );
$(document).on('click','#approve',function(){
//your code here
});
I find a quick dip into the DOM, and then running back into jQuery very handy for this problem:
// Construct some new DOM element.
$(whatever).html('... id="mynewthing"...');
// This won't work...
$("#mynewthing")...
// But this will...
$(document.getElementById("mynewthing"))...
This works by turning the DOM object directly into a selector. I like it because the approach is transparent in operation/intent.
Another alternative, simpler to understand, less powerful, also perfectly valid, is to simply bind the event while you create the element:
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
var $button = $('<button style ="button" id="approve">Approve</button>');
$button.on("click", function(){
var text = $('#post').val();
postsRef.push({'text':text});
$('#post').remove();
});
$('<div id="post">').text(posts.text).append($button).appendTo($('#feed'));
});
Another problem you are going to run into, assuming there will be more than one of these on a page, is that you are using IDs in the records. They're going to clash if they aren't unique.
A great alternative is to refer to these items with data-* tags or other identifying characteristics, such as css tags. But in your case, you don't need them at all!
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
var id = snapshot.name();
var $button = $('<button style="button">Approve</button>');
$button.on("click", function(){
// use parent.closest(...) in place of an ID here!
var text = $(this).parent().closest('textarea').val();
postsRef.push({'text':text});
$(this).parent().remove();
});
/* just an example of how to use a data-* tag; I could now refer to this element using:
$('#feed').find('[data-record="'+id+'"]') if I needed to find it */
$('<div data-record="'+id+'">').text(posts.text).append($button).appendTo($('#feed'));
});
I don't sure exactly what are you looking for. You can use .find() to select dynamically elements. I think .find() will look at the html structure again to get needed elements.
$("#button").click(function(e){
$(".parentContainer").find(".dynamically-child-element").html("Hello world");
});
Or
$(".parentContainer").find(".dynamically-child-element").html("Hello world"); // not in click event
So this is my demo

Create new element from selector?

How can I create a new element using just a selector? (e.g. .myclass, #myid or a:not(.someclass)) Basically there is no way for you to tell if the element is a div, span, li, an anchor, if it's a div with a class or with an id and so on.
In jQuery I know you can do $(selector) to get a usable DOM object. But how can this be done in JavaScript?
In jQuery I know you can do $(selector) to get a usable DOM object...
Not to create one. jQuery will do a search in the DOM for existing matches. You can do $("<div>") and such (note that's HTML, not a CSS selector) to create elements, but jQuery doesn't have a feature for creating elements from CSS selectors.
But how can this be done in JavaScript?
You'll have to parse the selector, and then use document.createElement with the tag name, and then set any classes or other things the selector describes on the new element.
CSS selectors aren't very hard to parse. You'll be able to find a lib that does it. (jQuery has Sizzle, which is a selector engine, built in and Sizzle is open source. It will naturally have code to parse selectors.)
Mootools does this.
new Element('#name.class')
yields
<div id=​"name" class=​"class">​</div>​
The answer appears to be that there is no built-in way of doing this. Maybe there’s a library which does the job.
However, it’s not to hard to write a function to create an element from a simple selector:
/* createElementFromSelector(selector)
================================================
Usage: element#id.class#attribute=value
================================================ */
function createElementFromSelector(selector) {
var pattern = /^(.*?)(?:#(.*?))?(?:\.(.*?))?(?:#(.*?)(?:=(.*?))?)?$/;
var matches = selector.match(pattern);
var element = document.createElement(matches[1]||'div');
if(matches[2]) element.id = matches[2];
if(matches[3]) element.className = matches[3];
if(matches[4]) element.setAttribute(matches[4],matches[5]||'');
return element;
}
var testitems = [
'div#id.class#attribute=value',
'div#id.class#attribute',
'div',
'div#id',
'div.class',
'#id',
'.class',
'#id.class',
'#whatever'
];
testitems.forEach(item => {
var element = createElementFromSelector(item);
console.log(element);
});
The tricky part is the regular expression. You can see it in detail here: https://regex101.com/r/ASREb0/1 .
The function only accepts selectors in the form element#id.class#attribute=value with the any of components being optional, as you see in the test items. I think including pseudo classes is probably pushing the friendship, but you might like to modify it to include multiple real classes.

Jquery each and Selector behaving differently

I created a function in Jquery which is supposed to center elements vertically (I could not do it using css, got tired and just made it programically ^^). The problem now is that I initially created it using .each, and then, since it was already creator, I tried calling it using the selector ($('something').center), but it is behaving differently for some reason.
Using the selector, it seems to be doing just the same to every element. It does it with the first element, and then just applies all values to the remaining elements. So, for example, my function takes the element height and does some operations with it, but the selector just takes the first one and then applies its parameters to everyone..
I'll keep using each since it works best right now, but I still can't understand why they are doing that..
Centering Function:
$.fn.center = function (){
/*If this is the highest element, or
if this element has full use of the width,
then there's no need to align it.
*/
if(this.height() == this.parent().height() ||
this.width() == this.parent().width())
{
this.css({
position : "relative",
top : 0
});
}
else //Should be aligned.
{
this.css({
position : "relative",
top : (this.parent().height()/2)-(this.height()/2)
});
}
return this; //Used for chaining.
};
Here's an example of what I mean ^^
http://jsfiddle.net/lrojas94/pmbttrt2/1/
For simple things, like just changing the CSS in the same way for all elements with the same class, you can call it directly without using .each(). For example:
$('.elem').css('color', '#fff');
But if each of the divs needs to end up with an individual value, you should use .each(). For example (sorry it's a bit weird):
var border = 1;
$('.elem').each(function() {
$(this).css('border', border + 'px solid #000');
border += 1;
});
Basically, if you don't use .each(), it'll check what you want to change (just once!) and apply it to all elements with that class. If you do use .each(), it'll do it individually for each element.
Simply put, this within a jQuery plugin function is not a DOM node. It's the jQuery object that wraps around all the nodes that were matched by the selector.
Your function's body should rather look like:
return this.each(function () {
var $el = $(this);
//centering logic for $el goes here
});

Selector ignoring elements contained in a specific element

I am currently working on a software plugin which scans a page for links in order to edit them. But there is a problem: I dont want to edit links that are contained in a specific element (in this case: an edit box). The elements contained in this edit box can also be nested, so parent might not be appropriate.
Is there any way to exclude elements via selector that are contained in a specific element?
You can run this plain JavaScript, it returns all elements with the matching pattern not in the container you specify.
var anchors = document.querySelectorAll('*:not(.editBox)>a.link');
Assuming your not wanted container has a class of "editBox" and you can change the matching "link" class to be any query selector you want, can be a plain 'a' for all anchor elements. I created a JSFiddle as a demo.
This doesn't all have to be on one selector. You could very simply use your regular selector to catch all the elements, and then execute a not() function to trim down the elements to only those you need.
var elems = $( "a" ); // all anchor links
elems = elems.not( ".ignore_me" ); // remove all links with the "ignore_me" class.
You could even combine these two into one command using function chaining:
var elems = $( "a" ).not( ".ignore_me" );
A third option that I feel is a little less readable would be something like this:
var elems = $( "a:not( .ignore_me )" );
References:
:not()
not()

JQuery Event Listeners in a For Loop

I am trying to create some basic button rollover functionality using Jquery and toggleClass. I am building a list of elements by cloning a DIV from my HTML and duplicating it multiple times (its populating a list of data from a database). To do this I am using a for loop. Here is the currently working code.
var displayNode = document.getElementById('phoneDisplayContainer');
for(var i=0; i<length; i++) {
//Clone the original container display.
var clonedDisplay = displayNode.cloneNode(true);
clonedDisplay.setAttribute('id', 'phoneDisplayContainer' + i);
//Remove hidden class from cloned Element. NOT CROSS BROWSER!
clonedDisplay.classList.remove('hidden');
var children = clonedDisplay.getElementsByTagName('div');
//Fill new nodes children containers with data.
children[1].innerHTML = contact.phone[i].type;
children[2].innerHTML = contact.phone[i].number;
children[3].setAttribute('onclick', 'PhoneUtility.edit(' + i + ');');
children[3].setAttribute('id', 'phoneEditDisplay' + i);
children[4].setAttribute('onclick', 'PhoneUtility.remove(' + i + ');');
//Hidden elements
var hidden = new Array(children[3], children[4]);
//Set rollover events.
clonedDisplay.setAttribute('onmouseover', '$("#' + children[3].id + '").toggleClass("hidden");');
clonedDisplay.setAttribute('onmouseout', '$("#' + children[3].id + '").toggleClass("hidden");');
//Append the new node to the display container
phoneContainer.appendChild(clonedDisplay);
}
}
Is there a way to use Jquery event listeners instead of having to set onmouseover and onmouseout directly on the element?
I tried this:
$(clonedDisplay).mouseover(function() {
$(children[3]).toggleClass('hidden');
});
With no luck. It just displays performs the rollover effect on the last element in the list. This is actually my first attempt at using jQuery so any other suggestions to ways I could jQuery inside the code would be helpful too.
EDIT: I'd also like to toggle multiple children from the arraylist mentioned in the for loop. How would I set this up? I can't seem to pass an array to the jquery command without getting errors.
The following code after your for loop should let you assign all the mouseover and mouseout handlers in one go to apply to all the clones:
$('div[id^="phoneDisplayContainer"]').mouseover(function() {
$(this).find("div").eq(3).toggleClass("hidden");
}).mouseout(function() {
$(this).find("div").eq(3).toggleClass("hidden");
});
// or, given that both handlers do the same thing:
$('div[id^="phoneDisplayContainer"]').on("mouseover mouseout", function() {
$(this).find("div").eq(3).toggleClass("hidden");
})
(If you're using jQuery older than 1.7 use .bind() instead of .on().)
The above says to find all the divs with an id beginning with "phoneDisplayContainer" and assign event handlers. Within the handler, find the fourth descendant div and toggle the class.
You don't show your HTML or CSS, but you could do this all in your CSS if you like. Assuming you can assign a common class ("parentDiv") to the divs that you want to trap the hover event on, and a common class ("childDiv") to their child div (the one to be hidden), you can do this:
.parentDiv .childDiv { visibility: hidden; }
.parentDiv:hover .childDiv { visibility: visible; }
(Obviously you can give more meaningful class names to fit your structure.)
Otherwise, again if you can assign those classes to the appropriate divs then after your loop you can do this with jQuery:
$(".parentDiv").on("mouseover mouseout", function() {
$(this).find(".childDiv").toggleClass('hidden');
});
Basically the same as what I said initially, but using classes for selectors. If you feel like I'm pushing a class-based solution on you that's because I am: it tends to make this sort of thing much easier.

Categories