Create variables from Html elements - javascript

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

Related

Jquery put elements in div

You need to put items in a div - <div style = 'flex-direction: column;'>.
Div needs to be created after p withid = "billing_city_field"
and closes after the p withid = "apartment_field".
Tried to do it with this function:
jQuery (document) .ready (function ($) {
$ ("# billing_city_field"). after ("<div style = 'flex-direction: column;'>");
$ ("# apartment_field"). after ("</ div");
});
But the div immediately closes. What should I do?
The issue is because you cannot append start/end tags separately. The DOM works with elements as a whole, so you need to create the entire div element in a single operation.
Given the description of your goal it looks like you're trying to wrap the existing content in a new div. As such you can use nextUntil() (assuming the target elements are siblings) and then wrapAll(). Try this:
jQuery($ => {
let $contents = $("#billing_city_field").nextUntil('#apartment_field').add('#apartment_field');
$contents.wrapAll('<div class="column" />');
});
Note the use of a class attribute in the above example, instead of applying inline style rules.
Question is not super clear but from what I can tell.
I think you have small misunderstanding what .after does with jQuery. After in this case is "structural" and not "time" related. If you check jQuery docs (https://api.jquery.com/after/) for this you can see basically what you need to do.
Simplest way to do this, if these things needs to created and don't exist already on body for example.
$(function(){
var p = $("<p id='apartment_field'>Paragraph test</p>");
$("body").append("<div id='billing_city_field' style='flex-direction: column;'></div>");
$("#billing_city_field").html(p);
});
I've added Paragraph test so result is visible easier.
And one more thing, not sure if it's error with copy/paste but make sure that # and id don't have space in-between like this.
$("#billing_city_field")
$("#apartment_field")
Edit: Looking at the comments maybe something like this, if they exist already? You should clarify the question more.
$("#billing_city_field").append($("#apartment_field").detach());

jQuery object where properties are DOM elements

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

Remove an element from the DOM based on a variable reference to it?

I'm dynamically creating a div like this:
var gameScoreDiv= document.createElement('div');
gameScoreDiv.innerHTML= 'Score: 0';
wrapperDiv.appendChild(gameScoreDiv);
Later I need to remove this div from DOM. How can I get rid of that div?
Is it possible to simply delete the gameScoreDiv variable and have it remove also the DOM element (I have a feeling the answer is no)?
2019 update
You can remove node with ChildNode.remove() now:
gameScoreDiv.remove()
It's supported by every major browser with the not surprising exception of IE (for which you can add a tiny polyfill though, if needed).
You can do:
gameScoreDiv.parentNode.removeChild(gameScoreDiv);
or, if you still have reference to the wrapperDiv:
wrapperDiv.removeChild(gameScoreDiv);
In jQuery it would be:
$(gameScoreDiv).remove();
but this will use the parentNode way, see the source.
You're looking for the removeChild method.
In your case I see that wrapperDiv is the parent element, so simply call it on that:
wrapperDiv.removeChild(gameScoreDiv);
Alternatively, in another scope where that isn't available, use parentNode to find the parent:
gameScoreDiv.parentNode.removeChild(gameScoreDiv);
you can give your dynamically created div an id, and later you can see if any element with this id exists, delete it. i.e.
var gameScoreDiv= document.createElement('div');
gameScoreDiv.setAttribute("id","divGameScore");
gameScoreDiv.innerHTML= 'Score: 0';
wrapperDiv.appendChild(gameScoreDiv);
and later:
var gameScoreDiv= document.getElementById('divGameScore');
wrapperDiv.removeChild(gameScoreDiv);
You can try this:
gameScoreDiv.id = "someID";
//Remove the div like this:
var element = document.getElementById('someID');
element.parentNode.removeChild(element);

How to loop though elements based on part of the dom name

I want to hide all the elements on the page that end in _dropMenu via javascript...so this is what i have
window.onload = function() {
hideNav();
};
function hideNav(){
myArray = element("_dropMenu");// this is what need changing
for (i=0;i<=5;i++)
{
i.style.visibility = 'hidden';
}
}
This is obviously wrong but how do I first get all the elements on the page that end with _dropMenu then loop through them and set them to hidden... I would prefer javascript since I only have prototype on the page but if I need to add jquery I will...
jQuery has a selector for finding elements that have an attribute that ends with a given string:
$('[id$="_dropMenu]')
This will be faster if you can narrow it by an element type (e.g. if all the elements you care about are divs, or some such) but will work as is.
Behind the scenes, jquery is just looping through a given set of elements, and checking whether element["id"].substring(element["id"].length-"_dropMenu".length)==="_dropMenu".
Just pointing out the Prototype is very similar to jQuery in this case:
$$('[id$="_dropMenu"]').invoke('hide');
Kudos Jishnu & JacobM for getting the selector first.

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