JavaScript Folding Menu Tree - javascript

This is a JavaScript function for menu tree. I would like to add more sub-menu in it, not only one sub-menu. What's x.all[0] and x.all[2]?
var head="display:''"
img1=new Image()
img1.src="fold.gif"
img2=new Image()
img2.src="open.gif"
function change(){
if(!document.all)
return
if (event.srcElement.id=="folding"){
var x=event.srcElement.parentElement
if (x.all[2].style.display=="none"){
x.all[0].src="open.gif"
x.all[2].style.display=''
alert(x.all[2].name )
}
else{
x.all[0].src="fold.gif"
x.all[2].style.display="none"
}
}
document.onclick=change

all is a collection of child elements belonging to a particular element. document.all returns all elements for a document. It is an IE only feature and will not work in other browsers.
In your code, x is event.srcElement.parentElement, so it's all property would be all the child elements belonging to that parent element. The [0] will return the first element in the collection and [2] will return the third element in the collection.
As mentioned before, this code will only work in Internet Explorer, so you should explore other cross browser methods to achieve what you're trying to do if you want better browser compatibility.

Related

Javascript remove item from DOM before rendering code

I'm trying to remove an element from my HTML document, which I'm able to do with the remove method, however, when console logging the NodeList with document.querySelectorAll() on some classes on elements that should've been removed, they're still showing up in the NodeList.
I need to remove an element from the webpage, but also from the NodeList, as if the element wasn't there initially on page load to prevent the rest of my application from thinking that it's there.
I would've thought that the remove method would've covered this, but unfortunately it doesn't, what am I missing and what's the workaround?
function removeElement (ident) {
const elem = document.querySelector(ident)
if (elem) {
elem.remove()
}
}
you have to get elements by their id name.
var elem = document.getElementById('myid');
elem.remove()
here 'myid' is the id of the item to be deleted.
if you want to delete it using query selector then take the help of elem's parent element.
let elem = document.querySelector(ident);
elem.parentElement.removeChild(elem);

Getting index of a node on click

I'm trying get the index of a tab in YUI using delegate along with the indexOf method - specifically I want to remove a tab on the click of an image housed inside of an li element:
var tabView = new Y.TabView({
srcNode: '#data-table'
});
...
//creating tabs
...
var removeTab = function(e) {
var tabList = e.container.all('li'); //returns a list of the 'li' elements/tabs
tab = tabView.indexOf(e.currentTarget);
alert(tab); //returns -1 (node not found)
//tabView.remove(tab);
}
Y.one('#data-table').delegate('click', removeTab, 'img');//on click of the img, launch removeTab
I don't believe YUI has a simpler way of doing this-most guides I've found are outdated or don't implement removing tabs the same way.
The problem is that the delegate handler is set on img element - so e.currentTarget will refer to an <img> element (that was clicked).
With e.container.all('li'), however, you retrieve the collection of <li> elements. No element in this collection, naturally, can be equal to <img>. That's why indexOf fails.
One possible solution is finding the <li> parent of <img> element first, then check its index:
var liClicked = e.currentTarget.ancestor('li');
var tabIndex = tabList.indexOf(liClicked);

reach a HTML element using javascript without getElementById

I'm new to javascript. I created this div called colorme. I can successfully color it via javascript. Now assuming i want to change the background of <p>...</p>, or <span>,etc how do i reach it via Javascript? (no jquery).
Like document.getElementById() would work on the div and i reach it. Now i cannot keep giving unique id's to all the elements. How do i reach the inner elements like <p> or <span>, etc?
<div id="colorme">
<p>Blah Vblah Blah Content</p>
<span>Blah Vblah Blah Content</span>
</div>
You can use the element that you've found as a context for getElementsByTagName.
var colorme = document.getElementById('colorme'),
spans = colorme.getElementsByTagName('span');
Note that spans is a NodeList -- similar to an array -- containing all the span elements within colorme. If you want the first one (indeed, the only one in your code sample), use spans[0].
You should check out the many DOM traversal functions provided in standard javascript.
Tutorial: http://www.quirksmode.org/dom/intro.html
Reference: http://reference.sitepoint.com/javascript/Node
and http://reference.sitepoint.com/javascript/Element
Although the answers do give good ways to do it for this specific case....
The issue you're facing is called DOM-traversal. As you know, the DOM is a tree, and you can actually traverse the tree without knowing in advance the element id/type/whatever.
The basics are as follows
el.childNodes to access a list of children
el.parentNode to access the parent element
nextSibling and previousSibling for next and previous sibling nodes
For further info, see [MDC DOM pages](
Here are three ways:
If you only care about decent browsers, document.querySelector (returns the first matching node) and document.querySelectorAll (returns a NodeList) - e.g. document.querySelector('#colorme p').
HTMLElement.getElementsByTagName() (returns a NodeList) - e.g. document.getElementById('colorme').getElementsByTagName('p')[0]
HTMLElement.children, etc. - document.getElementById('colorme').children[0] (.firstChild will probably be a text node, lots of fun DOM stuff to get into there, the quirksmode DOM intro linked to is good stuff).
It's quite simple: getElementsByTagName()?
You could use getElementsByTagName()
Loop through the children:
var div = document.getElementById('colorme');
var i, l, elem;
for (i = 0, l = div.childNodes.length; i < l; i++) {
elem = div.childNodes[i];
// Check that this node is an element
if (elem.nodeType === 1) {
elem.style.color = randomColorGenerator();
}
}
In this case you can use:
var colormeDiv = document.getElementById('colorme');
var e1 = colormeDiv.getElementsByTagName('p');
var e2 = colormeDiv.getElementsByTagName('span');
to get the two elements inside 'colorme' div.
getElementById is just one of JavaScript's DOM methods. It returns an HTMLElement DOM object which you can then query to find child, parent and sibling elements. You could use this to traverse your HTML and find the elements you need. Here's a reference for the JavaScript DOM HTMLObject.
[after answering, I realised this is no answer to your fully explained question, but it is the answer to the question raised in the title of your post!]
One nice way of doing this is declaring a global var on the top of your Javascript that refers to the document, which can then be used everywhere (in every function):
<html>
<head>
<script type="text/javascript">
// set a global var to acces the elements in the HTML document
var doc = this;
function testIt()
{
doc.blaat.innerHTML = 'It works!!';
}
</script>
</head>
<body>
<div id="blaat">Will this ever work..?!</div>
<button onclick="testIt()">Click me and you'll see!</button>
</body>
</html>
As my first impression when I got to 'getElemenyById()' was that it sounds like a function that will iterate through the DOM's element list until it finds the element you need; this must take some time. With the above example, you simply access the element directly.
I'm not sure if I'm really saving CPU / adding speed this way, but at least it feels that way :)

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

MooTools: Element disposal

Let's say I have two elements on a page. One is a div, and the other is its child, an achor. Let's say that I've added an event to that anchor via anchor.addEvent('click', ...). If I set the div's .innerHTML = '', does the 'click' event associated with the anchor get removed/disposed of/garbage collected?
It depends if you have still reference to "anchor" DOM instance. If so, it will stay in memory until all references are removed.
Test example:
var parent = new Element('div');
var child = new Element('div', {
events : {
click : function() {
alert('child clicked');
}
}
});
child.innerHTML = 'child content';
parent.appendChild(child);
document.body.appendChild(parent);
parent.innerHTML = 'parent content';
document.body.appendChild(child);
According to the MooTools API: destroy() is a method that:
Empties an Element of all its children, removes and garbages the Element. Useful to clear memory before the pageUnload.
I suspect that what happens to anchors removed when their parent elements are removed using innerHTML = '' is going to depend on the browser.
jQuery offers an empty() method, I am guessing other libraries probably offer methods too. You can see a pretty good discussion of this topic in Removing an element from DOM.
IMHO, you should use empty() instead of innerHTML = "".
The reference will remain like #nemisj said, but it will be "floating" and useless.
I did some tests here: test case, maybe you'll find interesting.

Categories

Resources