473,701 Members | 2,691 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Element-swapping method comparison


Please help me understand the differences, in semantics, browser
support and moral preferredness, between the following three methods
of swapping content in and out of a page via JavaScript. I would also
appreciate any general criticism you have to offer.

I don't know yet how to write the degradation-path code for browsers
that don't support the DOM methods I'm using, so there are some
commented-out paths below.

If the content contained form controls, then methods I and II would
cause hidden controls to be submitted, and method III would cause them
not to be submitted, correct?
Here is the page content. The upper area contains three buttons
that select which text is to be displayed in the lower area. Standard
HTML wrapper is omitted.

<!-- control area -->
<div id="control_are a">
<button id="button_1" onclick="do_but ton(1);">1</button>
<button id="button_2" onclick="do_but ton(2);">2</button>
<button id="button_3" onclick="do_but ton(3);">3</button>
</div>

<!-- content area -->
<div id="content_are a">
<div class="content" id="content_1"> Content box 1.</div>
<div class="content" id="content_2"> Content box 2.</div>
<div class="content" id="content_3"> Content box 3.</div>
</div>
Method I. Class swapping. Define two CSS classes, one "hidden"
and one "non-hidden"; the event-handler changes the className of
each div.

<style type="text/css">
div.content { display: none; }
div.content_unh idden { display: block; }
</style>

<script type="text/javascript">
var content_boxes = new Array();
// get the div objects
if (document.getEl ementById) {
for (var i = 1; i <= 3; i++) {
content_boxes[i] = document.getEle mentById("conte nt_" + i);
}
} else {
; // do something else when we don't have document.getEle mentById
}

function do_button(n) {
for (var i = 1; i <= 3; i++) {
// if div.className is not provided by the browser's DOM,
// setting it should be harmless, right?
content_boxes[i].className = (i == n) ? "content_unhidd en"
: "content";
}
}
</script>
Method II. Direct setting of the style.display property. Goodman
says this is DOM Level 2, not 1, and in particular setting
style.display to "block" is not supported by IE4, although "none"
is.

<script type="text/javascript">
var content_boxes = new Array();
// get the div objects
if (document.getEl ementById) {
for (var i = 1; i <= 3; i++) {
content_boxes[i] = document.getEle mentById("conte nt_" + i);
}
} else {
; // do something else when we don't have document.getEle mentById
}

// begin by hiding them all
if (content_boxes[1].style) {
for (var i = 1; i <= 3; i++) {
content_boxes[i].style.display = "none";
}
} else {
; // do something else when we don't have div.style
}

function do_button(n) {
if (content_boxes[1].style) {
for (var i = 1; i <= 3; i++) {
content_boxes[i].style.display = (i == n) ? "block"
: "none";
}
} else {
; // do something else when we don't have div.style
}
}
</script>
Method III. Moving of nodes in and out of the surrounding box by DOM
methods. I suppose it would be more efficient to wrap _all_ of this
in a check for DOM support, so that you don't have to check every
method?

<script type="text/javascript">
var bounding_box;
var content_boxes = new Array();
// get the div objects
bounding_box = document.getEle mentById("conte nt_area");
for (var i = 1; i <= 3; i++) {
content_boxes[i] = document.getEle mentById("conte nt_" + i);
}

// begin by hiding them all
while (bounding_box.h asChildNodes()) {
bounding_box.re moveChild(bound ing_box.firstCh ild);
}

function do_button(n) {
// prune out all the elements:
while (bounding_box.h asChildNodes()) {
bounding_box.re moveChild(bound ing_box.firstCh ild);
}
// then add back in the one we want
bounding_box.ap pendChild(conte nt_boxes[n]);
}
</script>
Thanks for your time,
--
Chris Jeris cj****@oinvzer. net Apply (1 6 2 4)(3 7) to domain to reply.
Jul 20 '05 #1
3 2080
Christopher Jeris wrote:
Please help me understand the differences, in semantics, browser
support and moral preferredness, between the following three methods
of swapping content in and out of a page via JavaScript.
Changing DOM structure would be theoretically best in swapping content,
since you really want to reflect a document fragment change; you can of
course accompany the new fragments with CSS to have a good presentation.

Now, CSS being more supported across user agents than DOM methods, means
that you'll see it used more often to achieve the content swapping
(since the visual rendering would appear to be the same in the end).

Eventually, most designers will however question the need to have
content swapping when they can make separate pages:-)
If the content contained form controls, then methods I and II would
cause hidden controls to be submitted, and method III would cause them
not to be submitted, correct?
I would tend to agree, provided the HTML is well-formed; now I don't
know why but I wouldn't be surprised to discover that with the buggy
version of browser X, elements with display set to none are not sent
along with the form submission:-)
Method I. Class swapping. Define two CSS classes, one "hidden"
and one "non-hidden"; the event-handler changes the className of
each div. div.content_unh idden { display: block; }
FYI underscores are not permitted in CSS identifiers.
// if div.className is not provided by the browser's DOM,
// setting it should be harmless, right?
Yes, but that doesn't mean your fallback mechanism will fire.
Method I is a good method, although the className property is not
supported in legacy browsers (Opera 6, Netscape 4, IE4 I think). However
changing the className can be quite resource-demanding when done frequently.
Method II. Direct setting of the style.display property. Goodman
says this is DOM Level 2, not 1, and in particular setting
style.display to "block" is not supported by IE4, although "none"
is.
A good method too, probably better supported by browsers than classNames
when you stick to "block" and "none"; certainly faster and the best
adapted to presentational swapping issue. Note that all display
properties are however far from being supported anywhere (e.g. table
layouts).
Method III. Moving of nodes in and out of the surrounding box by DOM
methods. I suppose it would be more efficient to wrap _all_ of this
in a check for DOM support, so that you don't have to check every
method?


Well it depends on your fallback solutions, whether you want to set a
general fallback solution or many ones... but yes. Feature detection is
a solid approach which however quickly burdens the code with numerous
checks. Doing the big part at some entry point can relieve other parts
of the code.

Method III is an excellent one when you truly want to swap content; it
tends to be quite supported since most user agents try now to respect
the W3C texts. Note that speed might also be an issue if you change
content in short intervals, since browsers may insert/remove nodes, or
working on orphaned nodes, at different speed.

As ever, the real problem you'll have to tackle will have its own
specificities, which may eventually force strange conceptions. Consider
filtering/sorting table elements; would it be better to change the
display or to remove nodes when filtering? What if you need to traverse
the filtered data frequently? If speed really matters would positioned
div be faster a table re-arranging?
Regards,
Yep.
Jul 20 '05 #2
Yann-Erwan Perio <y-*******@em-lyon.com> writes:
FYI underscores are not permitted in CSS identifiers.


*chris spends a frantic half-hour reading specs*

Underscores are indeed forbidden by the original CSS 2 spec!
Fortunately for me, this was apparently changed in a 2001 erratum[1]
and the CSS 2.1 working draft[2] permits them.

[1] http://www.w3.org/Style/css2-updates...12-errata.html
[2] http://www.w3.org/TR/CSS21/

--
Chris Jeris cj****@oinvzer. net Apply (1 6 2 4)(3 7) to domain to reply.
Jul 20 '05 #3
Christopher Jeris wrote:
FYI underscores are not permitted in CSS identifiers.
*chris spends a frantic half-hour reading specs*

Underscores are indeed forbidden by the original CSS 2 spec!
Fortunately for me, this was apparently changed in a 2001 erratum[1]
and the CSS 2.1 working draft[2] permits them.


*well it's high time for yep to read back some specs*

Thanks for the correction!
Jul 20 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3380
by: Igor | last post by:
Is there any way to resort and xml document using xslt based on element position. For example if I have xml like this: <root> <element> 1st thing </element> <element> 2nd thing </element> <element> 3rd thing </element> </root> would it be possible using xslt only to reverse it into:
0
1826
by: CJ | last post by:
I started with this schema: <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="response"> <xs:complexType> <xs:sequence> <xs:element name="SysTime" type="xs:string"/> <xs:element name="Item"> <xs:complexType> <xs:sequence>
2
4568
by: John Jørgensen | last post by:
Hi How do I express - in XSD - that an element can contain a sequenced list of elements, and one of these elements may occur (0-n times) at BOTH sequence position x AND y? Example: <PRIORITY sorting="900"/> <NAMEINFO> subtags and data
0
1491
by: Ingrid | last post by:
Am I right in thinking that datatyping at element level ie <xs:element name="num" type="xs:integer"> and specifying a choice of attribute values ie <xs:attribute name="kind"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="volume_number"/> <xs:enumeration value="page_range"/>
4
2391
by: Gordon Dickens | last post by:
I have target xml to generate from schema. All of the XML instances have the same global element i.e. <base>. I would like to combine all of the schemas into a single schema where I could generate any of the specific instances. sample schema one: <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="base">
5
3123
by: Patient Guy | last post by:
In my reading of the Strict and Transitional DTD for HTML 4.0, the table row (TR) elements are contained within table section elements: THEAD, TFOOT, and TBODY. The table section elements are the defined contents of the TABLE element. The TR element is not defined as an "immediate" or "direct" contained element of TABLE. Given that
4
2920
by: patrizio.trinchini | last post by:
Hi all, I'm new to XSLT and maybe my problem have a very trivial answer, but I need an expert that point me in the right direction. What I would obtain is to remove all the elements that have a child element with an attribute set at a given value; maybe an example is more self-explaining... Given the following input XML document:
3
11693
by: jparulan | last post by:
Hi All, I'm using SOAP3.0. I was able to successfully call a WSDL file and get a value properly. But when the WSDL changed to have a MULTIPLE <element name> it was failing. This code works BEFORE: strCurrency = oSOAP.eServeSearch(CSTR(Request.Form("T1"))) until the WSDL file changed to have more <element name> T1 is just a field that accepts a STRING
2
18145
by: mlb5000 | last post by:
I seem to be having issues validating an XML document using my schema. Both are below: The Schema: <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Receivers" > <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element ref="MulticastReceiver"/>
0
1321
Airslash
by: Airslash | last post by:
Hello, i've written the following XML Schema to validate my custom XML: <?xml version="1.0" encoding="utf-8"?> <xs:schema id="item" targetNamespace="http://www.tenforce.com/rest/item" xmlns="http://www.tenforce.com/schema/item.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ts="http://www.tenforce.com/rest/timestamp"
0
8649
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9229
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9083
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8934
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7824
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5904
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4662
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3102
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2398
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.