Top dom Questions

List of Tags

Ok.

So jQuery 1.6 has the new function prop().

$(selector).click(function(){
    //instead of:
    this.getAttribute('style');
    //do i use:
    $(this).prop('style');
    //or:
    $(this).attr('style');
})

or in this case do they do the same thing?

And if I do have to switch to using prop(), all the old attr() calls will break if i switch to 1.6?

UPDATE

See this fiddle: http://jsfiddle.net/maniator/JpUF2/

The console logs the getAttribute as a string, and the attr as a string, but the prop as a CSSStyleDeclaration, Why? And how does that affect my coding in the future?

Answered By: Tim Down ( 466)

Update 1 November 2012

My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team reverted attr() to something close to (but not exactly the same as) its old behaviour for Boolean attributes. John Resig also blogged about it. I can see the difficulty they were in but still disagree with his recommendation to prefer attr().

Original answer

If you've only ever used jQuery and not the DOM directly, this could be a confusing change, although it is definitely an improvement conceptually. Not so good for the bazillions of sites using jQuery that will break as a result of this change though.

I'll summarize the main issues:

  • You usually want prop() rather than attr().
  • In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work.
  • Properties are generally simpler to deal with than attributes. An attribute value may only be a string whereas a property can be of any type. For example, the checked property is a Boolean, the style property is an object with individual properties for each style, the size property is a number.
  • Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as value and checked: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the defaultValue / defaultChecked property).
  • This change removes some of the layer of magic jQuery stuck in front of attributes and properties, meaning jQuery developers will have to learn a bit about the difference between properties and attributes. This is a good thing.

If you're a jQuery developer and are confused by this whole business about properties and attributes, you need to take a step back and learn a little about it, since jQuery is no longer trying so hard to shield you from this stuff. For the authoritative but somewhat dry word on the subject, there's the specs: DOM4, HTML DOM, DOM Level 2, DOM Level 3. Mozilla's DOM documentation is valid for most modern browsers and is easier to read than the specs, so you may find their DOM reference helpful. There's a section on element properties.

As an example of how properties are simpler to deal with than attributes, consider a checkbox that is initially checked. Here are two possible pieces of valid HTML to do this:

<input id="cb" type="checkbox" checked>
<input id="cb" type="checkbox" checked="checked">

So, how do you find out if the checkbox is checked with jQuery? Look on Stack Overflow and you'll commonly find the following suggestions:

  • if ( $("#cb").attr("checked") === true ) {...}
  • if ( $("#cb").attr("checked") == "checked" ) {...}
  • if ( $("#cb").is(":checked") ) {...}

This is actually the simplest thing in the world to do with the checked Boolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:

if (document.getElementById("cb").checked) {...}

The property also makes checking or unchecking the checkbox trivial:

document.getElementById("cb").checked = false

In jQuery 1.6, this unambiguously becomes

$("#cb").prop("checked", false)

The idea of using the checked attribute for scripting a checkbox is unhelpful and unnecessary. The property is what you need.

  • It's not obvious what the correct way to check or uncheck the checkbox is using the checked attribute
  • The attribute value reflects the default rather than the current visible state (except in some older versions of IE, thus making things still harder). The attribute tells you nothing about the whether the checkbox on the page is checked. See http://jsfiddle.net/VktA6/49/.
387
Rob Stevenson-Leggett

I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.

var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;

var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);

I would like to know if there is a better way to do this using jQuery. I've been experimenting with:

var odv = $.create("div");
$.append(odv);
// And many more

But I'm not sure if this is any better.

Answered By: nickf ( 511)

here's your example in "one" line.

this.$OuterDiv = $('<div></div>')
    .hide()
    .append($('<table></table>')
        .attr({ cellSpacing : 0 })
        .addClass("text")
    )
;

Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about $("<div>") vs $("<div></div>") vs $(document.createElement('div')) as a way of creating new elements, and which is "best".

I put together a small benchmark, and here's roughly the results of repeating the above options 100,000 times:

jQuery 1.4, 1.5, 1.6

               Chrome 11  Firefox 4   IE9
<div>            440ms      640ms    460ms
<div></div>      420ms      650ms    480ms
createElement    100ms      180ms    300ms

jQuery 1.3

                Chrome 11
<div>             770ms
<div></div>      3800ms
createElement     100ms

jQuery 1.2

                Chrome 11
<div>            3500ms
<div></div>      3500ms
createElement     100ms

I think it's no big surprise, but document.createElement is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.

Update 2

Updated for jQuery 1.7.2 and put the benchmark on JSPerf which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!

http://jsperf.com/jquery-vs-createelement

342
dimarzionist

What is the reason browsers do not correctly recognize:

<script src="foobar.js" /> // self-closing script tag

Only this is recognized:

<script src="foobar.js"></script>

Is it breaking concept of XHTML support?

Note: This statement is correct at least for all IE(6-8 beta 2).

Answered By: squadette ( 150)

XHTML 1 specification says:

С.3. Element Minimization and Empty Element Content

Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use <p> </p> and not <p />).

XHTML DTD specifies script tags as:

<!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>

Hope it helps,

I need to debug a web application that uses jQuery to do some fairly complex and messy DOM manipulation. At one point, some of the events that were bound to particular elements, are not fired and simply stop working.

If I had a capability to edit the application source, I would drill down and add a bunch of Firebug console.log() statements and comment/uncomment pieces of code to try to pinpoint the problem. But let's assume I cannot edit the application code and need to work entirely in Firefox using Firebug or similar tools.

Firebug is very good at letting me navigate and manipulate the DOM. So far, though, I have not been able to figure out how to do event debugging with Firebug. Specifically, I just want to see a list of event handlers bound to a particular element at a given time (using Firebug Javascript breakpoints to trace the changes). But either Firebug does not have the capability to see bound events, or I'm too dumb to find it. :-)

Any recommendations/ideas? Ideally, I would just like to see and edit events bound to elements, similarly to how I can edit DOM today.

Answered By: Crescent Fresh ( 216)

See How to find event listeners on a DOM node.

In a nutshell, assuming at some point an event handler is attached to your element (eg): $('#foo').click(function() { console.log('clicked!') });

You inspect it like so:

  • jQuery 1.3.x

    var clickEvents = $('#foo').data("events").click;
    jQuery.each(clickEvents, function(key, value) {
      console.log(value) // prints "function() { console.log('clicked!') }"
    })
    
  • jQuery 1.4.x

    var clickEvents = $('#foo').data("events").click;
    jQuery.each(clickEvents, function(key, handlerObj) {
      console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }"
    })
    

See jQuery.fn.data (where jQuery stores your handler internally).

  • jQuery 1.8.x

    var clickEvents = $._data($('#foo')[0], "events").click;
    jQuery.each(clickEvents, function(key, handlerObj) {
      console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }"
    })
    
259
Morgan Cheng

How to check whether a JavaScript variable defined in cross-browser way?

I ran into this problem when writing some JavaScript utilizing FireBug logging. I wrote some code like below:

function profileRun(f) {
    // f: functions to be profiled
    console.profile(f.constructor);
    f();
    console.profileEnd(f.constructor);
}

It works fine in FireFox/FireBug, but it reports error in IE8 RC1. So, I'd like to do some checking whether console variable exists in the execution environment.

Below code works fine in FireFox, but not in IE8 RC1.

function profileRun(f) {
    if (console != undefined) {
        console.profile(f.constructor);
    }

    f();

    if (console != undefined) {
        console.profileEnd(f.constructor);
    }
}

However, if I do it this way. It works in IE8 RC1. Why?

function profileRun(f) {
    if (window.console != undefined) {
        console.profile(f.constructor);
    }

    f();

    if (window.console != undefined) {
        console.profileEnd(f.constructor);
    }
}

Is there any cross-browser way to check it?

Answered By: Jim Puls ( 472)

You want the typeof operator. Specifically:

if (typeof variable === 'undefined') {
    // variable is undefined
}
219
Navneet

I have a page where some event listeners are attached to input boxes and select boxes. Is there a way to find out which event listeners are observing a particular DOM node and for what event?

Events are attached using 1) prototype's Event.observe 2) DOM's addEventListener 3) as element attribute element.onclick

Answered By: Andrew Hedges ( 179)

If you just need to inspect what's happening on a page, you might try the Visual Event bookmarklet.

Update: Visual Event 2 available;

217
Tony Peterson

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.

Answered By: JW. ( 196)

Use document.activeElement, it is supported in all major browsers.

Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field.

Related links:

149
Christian Oudard

I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?

Answered By: Tim Down ( 89)

jQuery doesn't have a convenient function for this. You need to combine contents(), which will give just child nodes but includes text nodes, with find(), which gives all descendant elements but no text nodes. Here's what I've come up with:

var getTextNodesIn = function(el) {
    return $(el).find(":not(iframe)").addBack().contents().filter(function() {
        return this.nodeType == 3;
    });
};

getTextNodesIn(el);

Note: If you're using jQuery 1.7 or earlier, the code above will not work. To fix this, replace addBack() with andSelf(). andSelf() is deprecated in favour of addBack() from 1.8 onwards.

This is somewhat inefficient compared to pure DOM methods and has to include an ugly workaround for jQuery's overloading of its contents() function (thanks to @rabidsnail in the comments for pointing that out), so here is non-jQuery solution using a simple recursive function. The includeWhitespaceNodes parameter controls whether or not whitespace text nodes are included in the output (in jQuery they are automatically filtered out).

function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [], whitespace = /^\s*$/;

    function getTextNodes(node) {
        if (node.nodeType == 3) {
            if (includeWhitespaceNodes || !whitespace.test(node.nodeValue)) {
                textNodes.push(node);
            }
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
}

getTextNodesIn(el);
148
Darko Z

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 niggling 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?

Cheers

http://stackoverflow.com/a/268520/32943 has the benchmarks for the answers below

Answered By: strager ( 110)

I use $(document.createElement('div')); Seems fastest to me because jQuery doesn't have to identify it as an element and create the element itself.

You should really run benchmarks with different Javascript engines and weigh your audience with the results. Make a decision from there.