EzDevInfo.com

dom.js

Self-hosted JavaScript implementation of a WebIDL-compliant HTML5 DOM.

How do I find out which DOM element has the focus?

I would like to find out, in Javascript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and how?

The reason I was looking for this:

What I'm trying to do is make keys like the arrows and enter navigate through a table of input elements. Tab works now, but enter and arrows do not by default it seems. I've got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions.


Source: (StackOverflow)

What is the most efficient way to create HTML elements using jQuery?

Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of:

$("<div></div>");

However, I'm getting the feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective?

This answer has the benchmarks to the suggestions below.


Source: (StackOverflow)

Advertisements

Adding options to a select using Jquery/javascript

What's the easiest way to add an option to a dropdown using javascript? Can this work?

$("#mySelect").append('<option value=1>My option</option>');

Source: (StackOverflow)

JavaScript get input text value

I am working on kinda a search with JavaScript, I would use a form but it messes up something else on my page. I have this input text field:

<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

and this is my JavaScript:

<script type="text/javascript">
function searchURL(){
    window.location = "http://www.myurl.com/search/" + (input text value);
}
</script>

How do I get the value from the text field into JavaScript?


Source: (StackOverflow)

jQuery - Trigger event when an element is removed from the DOM

I'm trying to figure out how to execute some js code when an element is removed from the page:

jQuery('#some-element').remove(); // remove some element from the page
/* need to figure out how to independently detect the above happened */

is there an event tailored for that, something like:

jQuery('#some-element').onremoval( function() {
    // do post-mortem stuff here
});

thanks.


Source: (StackOverflow)

How to check if element exists in the visible DOM?

How do you test an element for existence without the use of the getElementById method? I have setup a live demo for reference. I will also print the code on here as well:

<!DOCTYPE html>
<html>
<head>
    <script>
    var getRandomID = function (size) {
            var str = "",
                i = 0,
                chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
            while (i < size) {
                str += chars.substr(Math.floor(Math.random() * 62), 1);
                i++;
            }
            return str;
        },
        isNull = function (element) {
            var randomID = getRandomID(12),
                savedID = (element.id)? element.id : null;
            element.id = randomID;
            var foundElm = document.getElementById(randomID);
            element.removeAttribute('id');
            if (savedID !== null) {
                element.id = savedID;
            }
            return (foundElm) ? false : true;
        };
    window.onload = function () {
        var image = document.getElementById("demo");
        console.log('undefined', (typeof image === 'undefined') ? true : false); // false
        console.log('null', (image === null) ? true : false); // false
        console.log('find-by-id', isNull(image)); // false
        image.parentNode.removeChild(image);
        console.log('undefined', (typeof image === 'undefined') ? true : false); // false ~ should be true?
        console.log('null', (image === null) ? true : false); // false ~ should be true?
        console.log('find-by-id', isNull(image)); // true ~ correct but there must be a better way than this?
    };
    </script>
</head>
<body>
    <div id="demo"></div>
</body>
</html>

Basically what the above code demonstrates is an element being stored into a variable and then removed from dom. Even though the element has been removed from the dom, the variable retains the element as it was when first declared. In other words, it is not a live reference to the element itself, but rather a replica. As a result, checking the variable's value (the element) for existence will provide an unexpected result.

The isNull function is my attempt to check for an elements existence from a variable, and it works, but I would like to know if there is an easier way to accomplish the same result.

Thanks very much in advance for any insight.

PS: I'm also interested in why JavaScript variables behave like this if anyone knows of some good articles related to the subject.


Source: (StackOverflow)

How to get a DOM Element from a JQuery Selector

I'm having an impossibly hard time finding out to get the actual DOMElement from a jquery selector. Sample Code:

<input type="checkbox" id="bob" />
  var checkbox = $("#bob").click(function() { //some code  } )

and in another piece of code I'm trying to determine the checked value of the checkbox.

  if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked )
    //do something.

And please, I do not want to do:

  if ( checkbox.eq(0).is(":checked"))
    //do something

That get's me around the checkbox, but other times I've needed the real DOMElement.


Source: (StackOverflow)

jQuery .live() vs .on() method for adding a click event after loading dynamic html

I am using jQuery v.1.7.1 where the .live() method is apparently deprecated.

The problem I am having is that when dynamically loading html into an element using:

$('#parent').load("http://..."); 

If I try and add a click event afterwards it does not register the event using either of these methods:

$('#parent').click(function() ...); 

or

// according to documentation this should be used instead of .live()
$('#child').on('click', function() ...); 

What is the correct way to achieve this functionality? It only seems to work with .live() for me, but I shouldn't be using that method. Note that #child is a dynamically loaded element.

Thanks.


Source: (StackOverflow)

Count immediate child div elements using jQuery

I have the following HTML node structure:

<div id="foo">
  <div id="bar"></div>
  <div id="baz">
    <div id="biz"></div>
  </div>
  <span></span>
</div>

How do I count the number of immediate children of foo, that are of type div? In the example above, the result should be two (bar and baz).


Source: (StackOverflow)

Creating a new DOM element from an HTML string using built-in DOM methods or prototype

I'm trying to create an element dynamically using an HTML string. Here's a simple example using both prototype and DOM:

// HTML string
var s = '<li>text</li>';
// DOM
var el1 = document.createElement(s);
// prototype
var el2 = new Element(s);
$('mylist').appendChild(el1);
$('mylist').appendChild(el2);

Both approaches insert an empty listitem to the list.

I know that using prototype's Element as a constructor requires a tagName and an optional attributes parameter, but I figured it may let me pass in an HTML string too.

However, MSDN states "You can also specify all the attributes inside the createElement method by using an HTML string for the method argument."... so I'm not sure what the problem is.

And yes, i know i could do this easily in jquery, unfortunately we're not using jquery. Am i overlooking something really simple here?


Source: (StackOverflow)

Do DOM tree elements with ids become global variables?

Working on an idea for a simple HTMLElement wrapper I stumbled upon the following for IE and Chrome:

For a given HTMLElement with ID in the DOM tree, it is possible to retrieve the div using its ID as variable name. So for a div like

<div id="example">some text</div>

in IE8 and Chrome you can do:

alert(example.innerHTML); //=> 'some text'

or

alert(window['example'].innerHTML); //=> 'some text'

So, does this mean every element in the DOM tree is converted to a variable in the global namespace? And does it also mean one can use this as a replament for the getElementById method in these browsers?


Source: (StackOverflow)

Remove all child elements of a DOM node in JavaScript

How would I go about removing all of the child elements of a DOM node in JavaScript?

Say I have the following (ugly) HTML:

<p id="foo">
    <span>hello</span>
    <div>world</div>
</p>

And I grab the node I want like so:

var myNode = document.getElementById("foo");

How could I remove the children of foo so that just <p id="foo"></p> is left?

Could I just do:

myNode.childNodes = new Array();

or should I be using some combination of removeElement?

I'd like the answer to be straight up DOM; though extra points if you also provide an answer in jQuery along with the DOM-only answer.


Source: (StackOverflow)

What is the difference between jQuery: text() and html() ?

What the difference between text() and html() functions in jQuery ?

$("#div").html('<a rel='nofollow' href="example.html">Link</a><b>hello</b>');

vs

$("#div").text('<a rel='nofollow' href="example.html">Link</a><b>hello</b>');

Source: (StackOverflow)

How to stop event propagation with inline onclick attribute?

Consider the following:

<div onclick="alert('you clicked the header')" class="header">
  <span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>

How can I make it so that when the user clicks the span, it does not fire the div's onclick event?


Source: (StackOverflow)

Why is setTimeout(fn, 0) sometimes useful?

I've recently run into a rather nasty bug, wherein the code was loading a <select> dynamically via JavaScript. This dynamically loaded <select> had a pre-selected value. In IE6, we already had code to fix the selected <option>, because sometimes the <select>'s selectedIndex value would be out of sync with the selected <option>'s index attribute, as below:

field.selectedIndex = element.index;

However, this code wasn't working. Even though the field's selectedIndex was being set correctly, the wrong index would end up being selected. However, if I stuck an alert() statement in at the right time, the correct option would be selected. Thinking this might be some sort of timing issue, I tried something random that I'd seen in code before:

var wrapFn = (function() {
    var myField = field;
    var myElement = element;

    return function() {
        myField.selectedIndex = myElement.index;
    }
})();
setTimeout(wrapFn, 0);

And this worked!

I've got a solution for my problem, but I'm uneasy that I don't know exactly why this fixes my problem. Does anyone have an official explanation? What browser issue am I avoiding by calling my function "later" using setTimeout()?


Source: (StackOverflow)