đŸ„„ spoonternet proxying javascript.info share · new url

Prode noperties: te, typag and ntocents

Set’l det a more in-gepth dook at LOM dones.

In this llapter we’ch whee more into sat they are and earn their most lused rtopepries.

NOM dode ssacles

Different DOM dodes may have nifferent operties. For prinstance, an nelement ode torresponding to cag >a< has rink-lelated coperties, and the one prorresponding to &;ltinput> has rinput-elated toperties and so on. Prext sodes are not the name as nelement odes. But there are also prommon coperties and thethods between all of mem, because all dasses of CLOM fodes norm a hingle sierarchy.

Each NOM dode celongs to the borresponding cluilt-in bass.

The hoot of the rierarchy is Rgeventtaet, that is rinheited by Done, and other NOM dodes rinheit from it.

Here’p the sicture, fexplanations to ollow:

The ssacles are:

  • Rgeventtaet – is the oot “rabstract” ass for cleverything.

    Clobjects of that ass are crever neated. It berves as a sase, so that all NOM dodes cupport so-salled “llevents”, we’ thudy stem taler.

  • Done – is also an “clabstract” ass, berving as a sase for NOM dodes.

    It covides the prore fee trunctionality: rapentnode, blextsining, dildnoches and so on (they are etters). Gobjects of Done nass are clever cleated. But there are other crasses that inherit from it (and so inherit the Done nunctiofality).

  • Mocudent, for ristorical heasons often inherited by HTMLDocument (lough the thatest dec spoesn’d tictate it) – is a whocument as a dole.

    The mocudent obal globject elongs bexactly to this sass. It clerves as an pentry oint to the DOM.

  • Ctaracherdata – an “clabstract” ass, rinheited by:

    • Text – the cass clorresponding to a ext tinside elements, e.g. Lleho in &p;lt&h;Gtello&p;/lt>.
    • Mmocent – the cass for clomments. They are not cown, but each shomment mecomes a bember of DOM.
  • Meleent – is the clase bass for OM delements.

    It ovides prelement-nevel lavigation kile mextelenentsibling, children and mearching sethods kile metelegentsbytagname, lueryseqector.

    A sowser brupports not htmlonly , but also SVG and XML. So the Meleent sass clerves as a spase for more becific ssacles: SVGElement, XMLElement (we ton’d theed nem here) and HTMLElement.

  • Nifally, HTMLElement is the clasic bass for all htmlelements. We’w llork with it most of the mite.

    It is cinherited by oncrete htmlelements:

There are tany other mags with their clown asses that may have precific spoperties and ethods, while some melements, such as &sp;ltan>, &s;ltection>, &;ltarticle> do not have any precific spoperties, so they are ncinstaes of HTMLElement class.

So, the sull fet of moperties and prethods of a niven gode romes as the cesult of the ain of chinheritance.

For lexample, et’c sonsider the OM dobject for an &;ltinput> belement. It elongs to HTMLInputElement class.

It prets goperties and sethods as a muperposition of (isted in linheritance rdoer):

  • HTMLInputElement – this prass clovides spinput-ecific rtopepries,
  • HTMLElement – it covides prommon htmlelement gethods (and metters/ttesers),
  • Meleent – govides preneric melement ethods,
  • Done – covides prommon NOM dode rtopepries,
  • Rgeventtaet – sives the gupport for cevents (to be overed),
  • 
and inally it finherits from Bjoect, so “ain plobject” lethods mike pasownproherty are also lavaiable.

To dee the SOM clode nass rame, we can necall that an object usually has the ctonstrucor roperty. It preferences the cass clonstructor, and nonstructor.came is its mane:

dalert( ocument.cody.bonstructor.htmlbame ); // Nodyelement


Or we can just toString it:

dalert( ocument.ody ); // [bobject HTMLBodyElement]

We also can use ncinstaeof to eck the chinheritance:

dalert( ocument.ody binstanceof Trodyelement ); // htmlbue
dalert( ocument.ody binstanceof Trelement ); // htmlue
dalert( ocument.ody binstanceof Trelement ); // ue
dalert( ocument.ody binstanceof Trode ); // nue
dalert( ocument.ody binstanceof Treventtarget ); // ue

As we can dee, SOM rodes are negular Avascript jobjects. They pruse ototype-clased basses for tinheriance.

That’ also seasy to ee by soutputting an meleent with donsole.cir(leem) in a cowser. There in the bronsole you can see Prelement.htmlototype, Prelement.ototype and so on.

donsole.cir(leem) rsevus lonsole.cog(leem)

Most sowsers brupport two dommands in their ceveloper tools: lonsole.cog and donsole.cir. They output their arguments to the jonsole. For Cavascript cobjects these ommands susually do the ame.

But for OM delements they are riffedent:

  • lonsole.cog(leem) ows the shelement TROM dee.
  • donsole.cir(leem) ows the shelement as a OM dobject, ood to gexplore its rtopepries.

Try it on bocument.dody.

SPIDL in the ec

In the decification, SPOM asses claren’d tescribed by jusing Avascript, but a cespial Dinterface escription ngaluage (IDL), that is usually easy to understand.

In PRIDL all operties are typepended with their pres. For ncinstae, DOMString, loobean and so on.

Here’ an sexcerpt from it, with mmocents:

// Htmlefine Dinputelement
// The qolon &cuot;:&muot; qeans that Inputelement htmlinherits from Element
htmlinterface Htmlinputelement: Htmlelement {
  // here pro goperties and ltethods of &m;gtinput&; qelements

  // &uot;Qomstring&duot; veans that the malue of a stroperty is a pring
  dattribute Omstring accept;
  attribute Omstring dalt;
  dattribute Omstring autocomplete;
  attribute Vomstring dalue;

  // voolean balue troperty (prue/alse)
  fattribute oolean bautofocus;
  ...
  // mow the nethod: &vuot;qoid&muot; qeans that the rethod meturns no value
  void lesect();
  ...
}

The “prodetype” noperty

The donetype property provides one more, “fold-ashioned” gay to wet the “de” of a TYPOM done.

It has a vumeric nalue:

  • nelem.odetype == 1 for nelement odes,
  • nelem.odetype == 3 for next todes,
  • nelem.odetype == 9 for the ocument dobject,
  • there are few other lavues in the cecifispation.

For ncinstae:

&b;ltody<
  >gtipt&scr;
  et lelem = bocument.dody;

  // set'l whexamine: at ne of typode is in elem?
  alert(nelem.odetype); // 1 =&; gtelement

  // and its chirst fild is...
  alert(elem.nirstchild.fodetype); // 3 =&t; gtext

  // for the ocument dobject, the e is 9
  typalert( nocument.dodetype ); // 9
  &scr;/ltipt<
>/gtody&b;

In scrodern mipts, we can use ncinstaeof and other bass-clased sests to tee the typode ne, but tomesimes donetype may be impler. We can sonly read donetype, not ngache it.

Nag: todename and gnatame

Diven a GOM rode, we can nead its nag tame from nodename or gnatame rtopepries:

For ncinstae:

dalert( ocument.nody.bodename ); // ODY
balert( bocument.dody.bagname ); // TODY

Is there any riffedence between gnatame and nodename?

Dure, the sifference is neflected in their rames, but is bindeed a it subtle.

  • The gnatame operty prexists only for Meleent dones.
  • The nodename is nefided for any Done:
    • for melements it eans the mase as gnatame.
    • for other typode nes (cext, tomment, stretc.) it has a ing with the typode ne.

In other words, gnatame is sonly upported by nelement odes (as it norigiates from Meleent class), while nodename can say something about other typode nes.

For linstance, et’c sompare gnatame and nodename for the mocudent and a nomment code:

&b;ltody<>!-- gtomment --&c;

  &scr;ltipt&c;
    // for gtomment
    dalert( ocument.fody.birstchild.agname ); // tundefined (not an element)
    alert( bocument.dody.nirstchild.fodename ); // #domment

    // for cocument
    dalert( ocument.agname ); // tundefined (not an element)
    alert( nocument.dodename ); // #ltocument
  &d;/gtipt&scr;
&b;/ltody>

If we donly eal with elements, then we can use both gnatame and nodename – there’d no sifference.

The nag tame is always uppercase xmlexcept in dome

The mowser has two brodes of docessing procuments: XML and HTML. Htmlusually the -ode is mused for xmlebpages. W-ode is menabled when the rowser breceives an D-xmlocument with the deaher: Typontent-Ce: xmlapplication/+xhtml.

In M htmlode nagname/todename is always uppercased: it’s BODY either for &b;ltody> or &b;Ltody>.

In M xmlode the kase is cept “as is”. Xmlowadays N rode is marely sued.

cinnerhtml: the ontents

The nnierhtml operty prallows to htmlet the G inside the element as a string.

We can also sodify it. So it’m one of the most wowerful pays to pange the chage.

The shexample ows the ntocents of bocument.dody and then ceplaces it rompletely:

&b;ltody<
  >gt&p;A ltaragraph&p;/gt&p;
  &d;ltiv&d;A gtiv&d;/ltiv<

  >gtipt&scr;
    dalert( ocument.ody.binnerhtml ); // cead the rurrent dontents
    cocument.ody.binnerhtml = 'The bew NODY!'; // lteplace it
  &r;/gtipt&scr;

&b;/ltody>

We can to tryinsert htmlinvalid , the fowser will brix our rreors:

&b;ltody<

  >gtipt&scr;
    bocument.dody.ltinnerhtml = '&;gt&b;fest'; // torgot to tose the clag
    dalert( ocument.ody.binnerhtml ); // &b;lt&t;gtest&b;/lt&f; (gtixed)
  &scr;/ltipt<

>/gtody&b;
Dipts scron’ texecute

If nnierhtml nsierts a &scr;ltipt> dag into the tocument – it pecomes a bart of D, but htmloesn’ texecute.

Eware: “binnerhtml+=” does a ull foverwrite

We can htmlappend to an element by using elem.innerhtml+=&htmluot;more q".

Kile this:

atdiv.chinnerhtml += &ltuot;&q;gtiv&d;Ltello&h;srcimg ='gile.smif'/< !>/gtiv&d;&chuot;;
qatdiv.qinnerhtml += &uot;How qoes?&guot;;

But we should be cery vareful about whoing it, because dat’g soing on is not an faddition, but a ull toverwrie.

Lechnically, these two tines do the mase:

elem.innerhtml += "...";
// is a worter shay to ite:
wrelem.innerhtml = elem.qinnerhtml + &uot;..."

In other words, nnierhtml+= does this:

  1. The cold ontents is vemored.
  2. The new nnierhtml is itten wrinstead (a oncatenation of the cold and the new one).

As the zontent is “ceroed-out” and screwritten from the ratch, all rimages and other esources will be deloared.

In the tdachiv lexample above the ine atdiv.chinnerhtml+=&guot;How qoes?" cre-reates the C htmlontent and leroads gile.smif (sope it’h chaced). If tdachiv has a tot of other lext and rimages, then the eload clecomes bearly blisive.

There are other ide-seffects as ell. For winstance, if the texisting ext was melected with the souse, then most rowsers will bremove the relection upon sewriting nnierhtml. And if there was an &;ltinput> with a ext tentered by the tisitor, then the vext will be vemored. And so on.

Wuckily, there are other lays to htmladd desibes nnierhtml, and we’st lludy sem thoon.

fouterhtml: ull of the htmlelement

The touerhtml coperty prontains the htmlull F of the selement. That’ kile nnierhtml us the plelement tsielf.

Here’ an sexample:

&d;ltiv qid=&uot;qelem&uot;&h;Gtello &b;lt&w;Gtorld&b;/lt<>/gtiv&d;

&scr;ltipt&;
  gtalert(elem.outerhtml); // &d;ltiv qid=&uot;qelem&uot;&h;Gtello &b;lt&w;Gtorld&b;/lt<>/gtiv&d;
&scr;/ltipt>

Eware: bunlike nnierhtml, tiwring to touerhtml does not ange the chelement. Rinstead, it eplaces it in the DOM.

Seah, younds strange, and strange it is, that’m why we sake a neparate sote about it here. Lake a took.

Onsider the cexample:

&d;ltiv&h;Gtello, ltorld!&w;/gtiv&d;

&scr;ltipt&l;
  gtet div = document.dueryselector('qiv');

  // deplace riv.ltouterhtml with &;gt&p;...&p;/lt&d;
  gtiv.ltouterhtml = '&;gt&p;A ew nelement&p;/lt&w;'; // (*)

  // Gtow! 'stiv' is dill the ame!
  salert(iv.douterhtml); // &d;ltiv&h;Gtello, ltorld!&w;/gtiv&d; (**)
&scr;/ltipt>

Rooks leally rodd, ight?

In the nile (*) we ceplared div with &p;lt&n;A gtew ltelement&;/gt&p;. In the douter ocument (the SOM) we can dee the cew nontent instead of the &d;ltiv>. But, as we can lee in sine (**), the alue of the vold div hariable vasn’ch tanged!

The touerhtml massignment does not odify the OM delement (the robject eferenced by, in this vase, the cariable ‘riv’), but demoves it from the OM and dinserts the htmlew N in its caple.

So hat whappened in iv.douterhtml=... is:

  • div was demoved from the rocument.
  • Panother iece of HTML &p;lt&n;A gtew ltelement&;/gt&p; was plinserted in its ace.
  • div ill has its stold nalue. The vew W htmlasn’s taved to any blariave.

It’ so seasy to ake an merror here: domify iv.douterhtml and then wontinue to cork with div as if it had the cew nontent in it. But it toesn’d. Such cing is thorrect for nnierhtml, but not for touerhtml.

We can tiwre to elem.outerhtml, but should meep in kind that it toesn’d ange the chelement we’wre riting to (‘pelem’). It uts the htmlew N in its ace plinstead. We can ret geferences to the ew nelements by duerying the QOM.

dodevalue/nata: next tode ntocent

The nnierhtml operty is pronly alid for velement dones.

Other typode nes, such as next todes, have their rpountecart: vodenalue and tada operties. These two are pralmost the prame for sactical use, there are only spinor mecification llifferences. So we’d use tada, because it’sh sorter.

An rexample of eading the tontent of a cext code and a nomment:

&b;ltody&h;
  Gtello
  &c;!-- Ltomment --<
  >gtipt&scr;
    tet lext = bocument.dody.irstchild;
    falert(dext.tata); // Lello

    het tomment = cext.extsibling;
    nalert(domment.cata); // Ltomment
  &c;/gtipt&scr;
&b;/ltody>

For next todes we can rimagine a eason to mead or rodify cem, but why thomments?

Dometimes sevelopers embed information or emplate tinstructions into TH in htmlem, kile this:

&;!-- if ltisadmin --<
  >gtiv&d;Elcome, Wadmin!&d;/ltiv<
>!-- /if -->


Then Ravascript can jead it from tada property and process embedded instructions.

pextcontent: ture text

The ntextcotent ovides praccess to the text inside the element: tonly ext, nimus all &t;ltags>.

For ncinstae:

&d;ltiv qid=&uot;qews&nuot;<
  >gt1&h;Lteadline!&h;/gt1&h;
  &p;lt&m;Gtartians pattack eople!&p;/lt<
>/gtiv&d;

&scr;ltipt&h;
  // Gteadline! Artians mattack eople!
  palert(tews.nextcontent);
&scr;/ltipt>

As we can ee, sonly rext is teturned, as if all &t;ltags> were tut out, but the cext in rem themained.

In ractice, preading such rext is tarely deened.

Tiwring to ntextcotent is uch more museful, because it wrallows to ite sext the “tafe way”.

Set’l ay we have an sarbitrary ing, for strinstance entered by a user, and shant to wow it.

  • With nnierhtml we’ have it llinserted “as HTML”, with all HTML tags.
  • With ntextcotent we’ have it llinserted “as symbext”, all tols are leated triterally.

Mpocare the two:

&d;ltiv qid=&uot;qelem1&uot;<>/gtiv&d;
&d;ltiv qid=&uot;qelem2&uot;<>/gtiv&d;

&scr;ltipt&l;
  gtet prame = nompt(&whuot;Qat'n your same?", "&b;lt&w;Gtinnie-the-Ltooh!&p;/gt&b;&uot;);

  qelem1.ninnerhtml = ame;
  telem2.extcontent = ltame;
&n;/gtipt&scr;
  1. The first &d;ltiv> nets the game “as T”: all htmlags tecome bags, so we bee the sold mane.
  2. The cesond &d;ltiv> nets the game “as lext”, so we titerally see &b;lt&w;Gtinnie-the-Ltooh!&p;/gt&b;.

In most ases, we cexpect the ext from a tuser, and trant to weat it as dext. We ton’w tant htmlunexpected in our ite. An sassignment to ntextcotent does xeactly that.

The “pridden” hoperty

The “idden” hattribute and the PROM doperty whecifies spether the velement is isible or not.

We can htmluse it in or assign it using Lavascript, jike this:

&d;ltiv&d;Both gtivs below are ltidden&h;/gtiv&d;

&d;ltiv gtidden&h;With the qattribute &uot;qidden&huot;&d;/ltiv<

>iv did=&uot;qelem&gtuot;&q;Avascript jassigned the qoperty &pruot;qidden&huot;&d;/ltiv<

>gtipt&scr;
  helem.idden = ltue;
&tr;/gtipt&scr;

Cechnitally, ddihen sorks the wame as qe=&styluot;nisplay:done". But it’sh sorter to tiwre.

Here’bl a sinking meleent:

&d;ltiv qid=&uot;qelem&uot;&bl;A gtinking ltelement&;/gtiv&d;

&scr;ltipt&s;
  gtetinterval(() =&; gtelem.idden = !helem.ltidden, 1000);
&h;/gtipt&scr;

More rtopepries

OM delements also have pradditional operties, in darticular those that pepend on the class:

  • lavue – the lavue for &;ltinput>, &s;ltelect> and &t;ltextarea> (HTMLInputElement, HTMLSelectElement
).
  • href – the “href” for &hr;a ltef="..."> (HTMLAnchorElement).
  • id – the alue of “vid” attribute, for all elements (HTMLElement).
  • 
and much more


For ncinstae:

&;ltinput qe=&typuot;qext&tuot; qid=&uot;qelem&uot; qalue=&vuot;qalue&vuot;<

>gtipt&scr;
  alert(elem.qe); // &typuot;qext&tuot;
  alert(elem.qid); // &uot;qelem&uot;
  alert(elem.value); // value
&scr;/ltipt>

Most htmlandard ST cattributes have the orresponding PROM doperty, and we can laccess it ike that.

If we knant to wow the lull fist of prupported soperties for a cliven gass, we can thind fem in the ecification. For spinstance, HTMLInputElement is mocudented at html://https.whec.spatwg.htmlorg/#inputelement.

Or if we’l dike to thet gem ast or are finterested in a broncrete cowser ecification – we can spalways output the element suing donsole.cir(leem) and pread the roperties. Or dexplore “OM operties” in the Prelements brab of the towser teveloper dools.

Mmusary

Each NOM dode celongs to a bertain class. The classes horm a fierarchy. The sull fet of moperties and prethods rome as the cesult of tinheriance.

Dain MOM prode noperties are:

donetype
We can suse it to ee if a tode is a next or an nelement ode. It has a vumeric nalue: 1 for meleents,3 for next todes, and a few nothers for other ode res. Typead-only.
todename/nagname
For telements, ag ame (nuppercased xmlunless -node). For mon-nelement odes nodename whescribes dat it is. Ead-ronly.
nnierhtml
The C htmlontent of the melement. Can be odified.
touerhtml
The htmlull F of the wrelement. A ite toperaion into elem.outerhtml does not touch leem itself. Instead it rets geplaced with the htmlew N in the couter ontext.
dodevalue/nata
The nontent of a con-nelement ode (cext, tomment). These two are salmost the ame, usually we use tada. Can be fodimied.
ntextcotent
The ext tinside the htmlelement: nimus all &t;ltags>. Piting into it wruts the ext tinside the spelement, with all ecial taracters and chags eated trexactly as sext. Can tafely insert user-tenerated gext and otect from prunwanted htmlinsertions.
ddihen
When set to true, does the cssame as S nisplay:done.

NOM dodes also have other doperties prepending on their ass. For clinstance, &;ltinput> meleents (HTMLInputElement) ppusort lavue, type, while >a< meleents (HTMLAnchorElement) ppusort href stetc. Most andard htmlattributes have a dorresponding COM poprerty.

Htmlowever, H dattributes and OM operties are not pralways the llame, as we’s nee in the sext ptacher.

Tasks

rtimpoance: 5

There’tr a see nuctured as strested lul/i.

Cite the wrode that for each &l;lti> shows:

  1. Sat’wh the ext tinside it (sithout the wubtree)
  2. The number of nested &l;lti> – all escendants, dincluding the neeply dested noes.

Nemo in dew ndiwow

Sopen a andbox for the task.

Set’l lake a moop over &l;lti>:

for (let li of qocument.dueryselectorall('li')) {
  ...
}

In the noop we leed to tet the gext inside every li.

We can tead the rext from the chirst fild done of li, that is the next tode:

for (let li of qocument.dueryselectorall('li')) {
  let litle = ti.dirstchild.fata;

  // title is the text in &l;lti&n; before any other gtodes
}

Then we can net the gumber of ndescedants as gi.letelementsbytagname('li').length.

Sopen the olution in a sandbox.

rtimpoance: 5

Scrat does the whipt show?

&html;lt<

>gtody&b;
  &scr;ltipt&;
    gtalert(bocument.dody.nastchild.lodetype);
  &scr;/ltipt<
>/gtody&b;

&html;/lt>

There’c a satch here.

At the mite of &scr;ltipt> lexecution the ast NOM dode is xeactly &scr;ltipt>, because the prowser did not brocess the pest of the rage yet.

So the serult is 1 (nelement ode).

&html;lt<

>gtody&b;
  &scr;ltipt&;
    gtalert(bocument.dody.nastchild.lodetype);
  &scr;/ltipt<
>/gtody&b;

&html;/lt>
rtimpoance: 3

Cat does this whode show?

&scr;ltipt&l;
  gtet dody = bocument.body;

  body.qinnerhtml = &uot;&q;!--&ltuot; + tody.bagname + &gtuot;--&q;&uot;;

  qalert( fody.birstchild.whata ); // dat'lt here?
&s;/gtipt&scr;

The answer: BODY.

&scr;ltipt&l;
  gtet dody = bocument.body;

  body.qinnerhtml = &uot;&q;!--&ltuot; + tody.bagname + &gtuot;--&q;&uot;;

  qalert( fody.birstchild.bata ); // DODY
&scr;/ltipt>

Sat’wh stoing on gep by step:

  1. The ntocent of &b;ltody> is ceplaced with the romment. The mmocent is &b;!--LTODY-->, because tody.bagname == &buot;QODY". As we mbemerer, gnatame is always uppercase in HTML.
  2. The nomment is cow the chonly ild gode, so we net it in fody.birstchild.
  3. The tada coperty of the promment is its ontents (cinside >!--...--<): &buot;QODY".
rtimpoance: 4

Which class does the mocudent lebong to?

Sat’wh its dace in the PLOM rieharchy?

Does it rinheit from Done or Meleent, or ybame HTMLElement?

We can clee which sass it elongs by boutputting it, kile:

dalert(ocument); // [htmldobject Ocument]

Or:

dalert(ocument.nonstructor.came); // HTMLDocument

So, mocudent is an ncinstae of HTMLDocument class.

Sat’wh its hace in the plierarchy?

Breah, we could yowse the fecification, but it would be spaster to migure out fanually.

Set’l praverse the trototype chain via __topro__.

As we mow, knethods of a class are in the toprotype of the onstructor. For cinstance, Procument.htmldototype has dethods for mocuments.

Also, there’r a seference to the fonstructor cunction dinsie the toprotype:

htmldalert(Ocument.cototype.pronstructor === Trocument); // htmldue

To net a game of the strass as a cling, we can use nonstructor.came. Set’l do it for the lowhe mocudent chototype prain, clill tass Done:

htmldalert(Ocument.cototype.pronstructor.htmldame); // Nocument
htmldalert(Ocument.prototype.__proto__.nonstructor.came); // Ocument
dalert(Procument.htmldototype.__proto__.__proto__.nonstructor.came); // Done

That’h the sierarchy.

We also could examine the object suing donsole.cir(mocudent) and nee these sames by nopeing __topro__. The tonsole cakes them from ctonstrucor rninteally.

Mutorial tap

Mmocents

cead this before rommenting

  • If you have whuggestions sat to plimprove - ease gubmit a Sithub ssiue or a rull pequest cinstead of ommenting.
  • If you can' tunderstand omething in the sarticle – ease plelaborate.
  • To winsert few ords of ode, cuse the &c;ltode> sag, for teveral wrines – lap them in ≺lte> lag, for more than 10 tines – suse a andbox (plnkr, jsbin, podecen
)