jQuery object where properties are DOM elements - javascript

I'm looking for a more succint and possibly more jQuery-e way of doing the following.
I have an object lbl which is a div. Contained within the div is a span tag that is the firstName and lastName property of the lbl object. So, so far we have the following HTML:
<div class="label">
<span class="firstName">John</span>
<span class="lastName">Doe</span>
</div>
Now consider the following fiddle http://jsfiddle.net/VfErV/
$('#btnSubmit').click(function ()
{
var lbl = $('<div>').addClass('label');
//I need to be able to access the child elements of the parent div
//via the dot operator
firstName = $('<span>').text('test1').addClass('firstName');
lastName = $('<span>').text('test2').addClass('lastName');
lbl.append(firstName);
lbl.append(lastName);
lbl.firstName = firstName;
lbl.lastName = lastName;
$('#page').append(lbl);
console.log(lbl.firstName.text());
//span tag is never added to the div
var lbl2 = $('<div>').addClass('label');
lbl2.firstName = $('<span>').text('test2').addClass('firstName');
$('#page').append(lbl2);
});
Please refer to the fiddle for behavior. I need to be able to control font-sizes, borders, etc. on the child objects of the parent div container, lbl, and have the appear on the page as normal DOM elements. All of the JS up until the first lbl control is appended to the page works. This looks clunky to me, though. Is there a better way to have child elements of a DOM element be properties of the parent object more easily/succintly?

You asked for a more jQuery-way to do this. Here's how you could create your structure:
$('#btnSubmit').click(function () {
var lbl = $('<div>').addClass('label');
lbl.html('<span class="firstName">test1</span><span class="lastName">test2</span>');
$('#page').append(lbl);
// Then, to retrieve that data, you can just do something like this
console.log(lbl.find(".firstName").text());
});
Then, anytime you want to get the firstName from a given label div, you just use .find("firstName") to get that object and then get its text.
Best practices generally just use the structure of the DOM and find things as needed in the DOM rather than make new duplicate ways to access everything. For 99% of what we do, accessing things through the DOM is plenty fast and doesn't require creation and duplication of another way to get to the data. And, jQuery makes it pretty easy to find things in the DOM as long as you have enough id or class markers to identify what you're looking for (which you do).

Related

Create variables from Html elements

Is it possible to get all the elements from a webpage, and make a variable for each one? can you make variables within an each function and name them the same as their element name?
Yes, but be careful.
It is useful to store an element reference in a variable if it's present at load time and not changed later, but removing the div after load would cause your variable to return undefined. If the div is added after the variable is declared, you will also encounter an error.
Have a read here.
As you said, it's just for fun.. so I think that this should do the trick:
$("*").each(function() {
const elmnt = $(this);
const id = elmnt.attr("id");
if(id) {
window[id] = elmnt;
}
});
This will only create variables for the DOMs that have the id defined. But you can change the rule the way you want.
Use:
var div = $('div');
div.click();
If you wanted to bind the click event to all div elements you could easily just do:
var div = $('div');
div.click(function(){
//do something
});
A good way to shorten the jQuery selector and overhead and page performance is to use VanillaJS: http://vanilla-js.com/
Selecting object is one of the easiest thing to do with vanilla JS. I don't know what is your use case but a lot of what jQuery does is never used. If you are looking for optimization, try to live without it for a while and you might be surprised. Here are some out of the box ways to get elements in short variables.
Get all divs in your document:
var divs = document.querySelectorAll('div');
Get the first div only:
var div = document.querySelector('div');
Get a specific div:
var div = document.getElementById('somediv');
This way you can control everything (a la carte variables, rather than trying to solve all problems you might not need to solve).

jquery - mix variable referencing a dom element with selector

I usually create variables for frequently reused DOM elements like this:
var $dom_element = $('#dom_element);
where this is my setup:
<div id="dom_element">
<div class="child_element">
<div class="child_element">
</div>
what I'm wondering is if I can mix this variable with a subselector to get child elements. I guess it would be something like this:
var $child_element = $($dom_element + ' .child_element);
And if so, is there any speed benefit to doing this versus just saying:
$('.child_element);
considering the fact that both of these elements might be deeply nested in a large site?
With
var $dom_element = $('#dom_element);
I would use the following to get the child elements
var $child_element = $dom_element.find(".child_element");//I prefer this one, it is easier to read.
or
var $child_element = $(".child_element", $dom_element);
From my research/reading, it appears that setting an element to a variable is best if you are going to reference it many times. That way jQuery does not have to search the DOM many times.
Regarding your selectors, you can get yourself into trouble when using a bare class as a child selector. What if you have multiple child nodes using that same class?
.find() works, as others have suggested. You could alternatively use .children():
var $kids = $dom_element.children('.child_element');
http://api.jquery.com/children/
The difference between .find() and .children() is that .children() will only look one level down the DOM tree. .find() will recursively run through all possible child nodes to match your selector.

Accessing elements inside dynamically created divs with HTML/Javascript

I'm quite new to javascript and JQuery programming. Usually, to access elements I give them an id, so I can get them like $("#"+id).blabla().
But now I need to dynamically create a div, and access elements inside it.
Something like
<div id="automaticallyGeneratedId">
<div ???></div> <!-- first div -->
<div ???></div> <!-- second div -->
</div>
What are the best practices to access and identify each of the inner divs?
I generate another id for them?
Or what?
I don't have the theory of selectors fully clear.
edit: modified the question from identifying a single inner div to identifying divs amongs many of them
You can maintain a pattern when you're generating id. For example:
if you always generate id like: myid1, myid2,myid3...
<div id="myid1">
<div></div>
</div>
<div id="myid2">
<div></div>
</div>
......
then you can try:
$('div[id^=myid]').find('div').foo();
OR
$('div[id^=myid] div').foo();
Here, ^= is start with selector, so div[id^=myid] will select div whose id start with myid.
You can also use Contain word selector which is ~= and use like $('div[id~=myid]'). This will select div with id contains word myid.
Instead of id if you want to use other attribute eg. name then change selector like:
$('div[name^=myid]') or $('div[name~=myid]').
It's usually a good practice that if you already have a reference to that outer div to just search from there using find.
You can give it an id, or if you want to use a more general approach you can use classes.
<div class="subdiv">...
$('#automaticallyGeneratedId').find('div.subdiv')
Usually, when you create them, you can assign event handlers and the likes straight on them. Like this:
var div = $( '<div></div>' );
div.on( 'click', function() {
// Do something when the generated div is clicked
});
// Then, add it to the DOM
$( 'body' ).append( div );
You don't need to bother selecting them with ID or classes, they're already available in your code.
Another way is to use event bubbling to handle newly created elements of the same class. A good link about this is this one: http://beneverard.co.uk/blog/understanding-event-delegation/
Many ways you can create an element and give him an Id or Class, or use the DOM to access it..
$("html").prepend('<div id="foo"></div>');
$("#foo").doSomething();
another way
$("#automaticallyGeneratedId").find("div").doSomething();
To access the div in the element with the id:
$("#automaticallyGeneratedId div").whatever
If you cache the divs you could use something like:
var myDiv1Child = $('div', myDiv1);
Create a delegated listener and within the listener you can find the element by doing this
//If a div inside the parent is clicked then execute the function within
$('.PARENT_CLASS').click("div", function(){
//This variable holds all the elements within the div
var rows = document.querySelector('.PARENT_CLASS').getElementsByTagName('div');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
console.log(this); //The element you wish to manipulate
}
}
});

jQuery - How to link together a DOM element and a Javascript object?

I want to be able to link a javascript object with a dom element but cant find a way for this to be done properly. An example: say when opening a page with an inventory it loads all the items contained in it and when I hover over the images inside it creates a small tooltip with some information. Well there will be much of these items on the page and i want to be able to link the DOM element with an object so i can access its properties easily. I hope im explaining my self properly.
say I had this inside an inventory:
<div id="slot1"><img id="item1"></div>
<div id="slot2"><img id="item2"></div>
and say i have a javascript object called slot1 and slot2:
the object slot1 has all the properties that need to be shown in the tooltip so i would like to do something like this in the mouseover event:
this.showTooltip()
any help would be great ty if i need to explain it better just say!
-Thaiscorpion
Use jQuery data:
$("div.hasToolTip").hover(
function() {
//Get the associated data with the DOM element
//with $(this).data(someKey)
showToolTip($(this).data('toolTipInformation'));
},
function() {
//Here you can hide all tooltips
}
);
Obviously, before you can register this event, you have to assign the object to every DOM element with $(selector).data(key, value).
These example expects that every DOM element which should have a tooltip has a class named .hasToolTip.
Look at the jQuery documentation for more information about the .data() function.
Just have the javascript object know the ID of the object it's watching.
function Tooltipper(divID) {
this.id = divID;
}
Tooltipper.prototype.showTooltip = function () {
// do tooltip stuff
$('#' + this.id).tooltip(); // assuming that it has a tooltip thing
};
var slot1 = new Tooltipper('slot1'),
slot2 = new Tooltipper('slot2');
And then:
slot1.showTooltip();
Or better yet, instead of passing in the ID, pass in the object:
var slot1 = new Tooltipper($('#slot1'));
This way you don't have to do a DOM lookup each time.

javascript get child by id

<div onclick="test(this)">
Test
<div id="child">child</div>
</div>
I want to change the style of the child div when the parent div is clicked. How do I reference it? I would like to be able to reference it by ID as the the html in the parent div could change and the child won't be the first child etc.
function test(el){
el.childNode["child"].style.display = "none";
}
Something like that, where I can reference the child node by id and set the style of it.
Thanks.
EDIT: Point taken with IDs needing to be unique. So let me revise my question a little. I would hate to have to create unique IDs for every element that gets added to the page. The parent div is added dynamically. (sort of like a page notes system). And then there is this child div. I would like to be able to do something like this: el.getElementsByName("options").item(0).style.display = "block";
If I replace el with document, it works fine, but it doesn't to every "options" child div on the page. Whereas, I want to be able to click the parent div, and have the child div do something (like go away for example).
If I have to dynamically create a million (exaggerated) div IDs, I will, but I would rather not. Any ideas?
In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():
function test(el){
el.querySelector("#child").style.display = "none";
}
For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.
As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").
This works well:
function test(el){
el.childNodes.item("child").style.display = "none";
}
If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.
If the child is always going to be a specific tag then you could do it like this
function test(el)
{
var children = el.getElementsByTagName('div');// any tag could be used here..
for(var i = 0; i< children.length;i++)
{
if (children[i].getAttribute('id') == 'child') // any attribute could be used here
{
// do what ever you want with the element..
// children[i] holds the element at the moment..
}
}
}
document.getElementById('child') should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.
edit : see this page - ids MUST be unique.
edit edit : alternate way to solve the problem :
<div onclick="test('child1')">
Test
<div id="child1">child</div>
</div>
then you just need the test() function to look up the element by id that you passed in.
If you want to find specific child DOM element use method querySelectorAll
var $form = document.getElementById("contactFrm");
in $form variable we can search which child element we want :)
For more details about how to use querySelectorAll check this page

Categories

Resources