Introducción a Document Object Model (DOM)

¿Qué es DOM?

DOM = Document Object Model o Modelo de documento objetos.

DOM → estándar creado por la W3C (World Wide Web Consortium) que nos permite acceder a los documentos desde JavaScript (u otros lenguajes).

DOM → Es la estructura jerárquica (similar a un árbol genealógico) que representa nuestro documento web en forma de esquema. Este esquema contiene todos los nodos (TAGs) que compone una página HTML.

¿Qué son los nodos?

Los nodos son cada uno de los elementos de nuestro documento. Por ejemplo, la etiqueta HTML es un nodo, la etiqueta HEAD o la etiqueta BODY también lo son. E incluso sus hijos, por ejemplo, dentro de BODY la etiqueta H1 o dentro de HEAD la etiqueta TITLE también son hijos.

¿Para qué se utiliza el DOM?

El DOM, se crea con la finalidad de poder identificar y permitirnos trabajar (modificando estilos, el contenido, añadiendo nodos hijos, etc) sobre todos los elementos (conocidos como nodos en DOM) de nuestro documento HTML.

Accediendo a Root Node

Si creamos un documento HTML con la estructura básica de HTML5:

Lo abrimos desde el navegador y vamos al inspector, podemos ver si escribimos document se nos subraya todo el documento HTML.

Esto es debido a que con DOCUMENT estamos seleccionando todo el documento web, es el primer nodo (elemento) de nuestro DOM, el Root Node (como una especie de dios, que engloba al resto y del que depende todos los elementos de nuestro documento).

De hecho, si ejecutamos document (pulsando enter) desde la consola de DevTools, podemos ver de document cae toda nuestra web, para ser más concretos, todo nuestro documento index.html.

Como ya hemos visto anteriormente desde la consola del navegador ejecutamos nuestro JavaScript, por lo que, podemos acceder al DOM, también desde JavaScript.

Para ello, asociamos un archivo de JS a nuestro documento HTML y trabajamos directamente con él:

Si ahora, hacemos un console.log de document, en nuestro archivo de JS:

Y recargamos nuestra web en el inspector del navegador, podemos ver que estamos en el mismo punto que antes:

DOM se crea para permitirnos trabajar sobre el documento HTML desde lenguajes de programación (en nuestro caso JavaScript) con el fin de editar estilos, cambiar el contenido de los nodos, etc.

Seleccionando un elemento con getElementsByTagName:

Si intentamos acceder al nodo BODY, realizando lo mismo que hemos hecho desde document anteriormente, podemos ver que nos arroja un error que nos indica que no está definido y, por tanto, no nos deja acceder a él:

¿Porque se produce esto? Debido a que para acceder a él tenemos que trabajar con nuestro document que es el nodo root (llamar a root node, a dios, el padre de todos los demás nodos).

¿Como lo vamos a hacer? Existen algunas maneras distintas que son totalemente válidas de acceder al body pero ninguna es consiste en escribirlo “a pelo”. En este caso, vamos a acceder al nodo BODY mediante a su nombre de Etiqueta <BODY> sin los <>.

Si ahora vamos al navegador, podemos ver que ahora sí que finalmente hemos accedido al elemento:

Seleccionando varios elementos de un mismo tipo con getElementsByTagName:

Si modificamos nuestro HTML y le añadimos otro título H1, nos encontramos que ahora tenemos dos títulos H1:

Vamos a seleccionarlos desde DOM, en este caso, utilizaremos otra vez con getElementsByTagName.

Tener dos títulos significa vez vamos a recibir varios nodos (elementos HTML).

Además de ver como se trabaja/selecciona varios nodos a la vez, vamos a ver otra manera de trabajar, guardando en variables el resultado que recibimos en la lista HTMLCollection.

Estos nodos se guardan en una lista HTMLCollection, (HTMLCollection = una node list o lista de nodos) y no un arrays, es importante no confundirlos. Por tanto, para recorrer varios elementos necesitamos transformar nuestro HTMLCollection en un Array para recorrerlo con un form Each:

Otra opción que nos aportará el mismo resultado si no queremos realizar la conversión de la lista HTMLCollection a un array podría ser:

El resultado de ambos será:

Seleccionando un elemento por ID getElementById

GetElementById si nos fijamos está escrito en singular, nos permite seleccionar solo un elemento. ¿Qué elemento? Pues el elemento sobre el que especifiquemos dicho Id.

Vamos a ver un ejemplo, si modificamos nuestro HTML y le añadimos un id a nuestro párrafo:

Hasta ahora, hemos mostrado nodos por consola. Pero con DOM, podemos hacer cosas más potentes. Vamos a seleccionar el p con id=”parrafo” y además de imprimir el nodo como hasta  ahora por consola, vamos a imprimir solamente le texto que contiene, luego modificaremos ese texto con (innerHTML) y finalmente, volveremos a imprimir ese texto. Podemos ver que, sin muchas complicaciones, podemos sacar el valor de un nodo con un id:

El resultado será:

Si nos fijamos acabamos de cambiar el contenido del nodo con id párrafo de nuestro documento HTML, desde JavaScript con DOM.

Seleccionando elementos con querySelectorAll y un elemento en particular con querySelector

Si añadimos varios hipervinculos:

Con querySelectorAll, podemos seleccionar todos los enlaces de un mismo tipo. Además de ello, vamos a modificar su estilo cambiando su color a rojo. Vamos a verlo:

Nos devuelve una NodeList similar al HTMLCollection con el que ya estamos acostumbrados a trabajar.

Si utilizamos querySelector, seleccionaremos únicamente el primer elemento que sea un enlace de nuestra página web. Y además de ello, también le cambiaremos el tamaño a dicho enlace para diferenciarlo del resto. Vamos a ver un ejemplo:

El resultado será:

Seleccionando elementos por su clase con getElementsByClassName

Sobre el mismo HTML anterior:

Vamos a ello:

Añadiendo un nodo (LI) a una lista (UL) con DOM

Si sobre el siguiente HTML:

Queremos añadir un LI hijo podemos hacer:

El resultado será:

Cambiando la clase de un nodo a otra de una hoja CSS (Toggle Class)

Hasta ahora, hemos trabajado hemos modificado nuestros estilos directamente con el DOM desde JS. Para acabar este artículo, vamos a ver la mejor manera más recomendada de realizar estas modificaciones de los estilos mediante a lo que se conoce como un toggle class (cambio de clase) para ello, vamos a crear una hoja de estilos CSS que contendrá dos estilos para nuestra lista.

De esta manera, separamos por capas como ya hacíamos con HTML, CSS y JS y cada una de las capas hace su función. También evitamos que se pisen los estilos entre el CSS y el que añadimos nosotros con DOM y JS. Y así, tan solo tenemos que cambiar la clase que tenemos asociada actualmente de archivo de CSS por la nueva sobre la que trabajamos el nodo mediante a DOM y JS.

Empezamos por el HTML:

El CSS contendrá:

Si cargamos la web podemos ver, que tenemos una lista que ordena los elementos numéricamente:

Vamos a añadirle a la lista UL la clase .liLowerAlpha y a remover la clase .liDecimal con el fin de que se vean los elementos de la lista ordenados alfabéticamente:

Espero que os guste el artículo y que DOM os haya quedado un poco más claro. Muchas gracias por la lectura. ¡Saludos, hasta pronto!

81 comentarios

  1. Magnificent website. A lot of helpful information here.
    I’m sending it to some buddies ans also sharing in delicious.

    And obviously, thanks to your sweat!

  2. Aw, this was an incredibly nice post. Taking a few minutes and actual
    effort to make a good article? but what can I say?
    I procrastinate a whole lot and don’t seem to get
    nearly anything done.

    Here is my web page – psicura.it

  3. Wow! Finally I got a blog from where I know how to truly take valuable data regarding my study
    and knowledge.

  4. Hi there Dear, are you in fact visiting this web page
    on a regular basis, if so afterward you will absolutely obtain good
    know-how.

    Feel free to visit my web site – The Skin Company Cream Reviews

  5. It is the best time to make some plans for the future and it is time to be happy.
    I have read this post and if I could I desire to suggest you some interesting
    things or suggestions. Perhaps you can write
    next articles referring to this article. I desire to read
    more things about it!

    Here is my web blog; Derma Ella Advanced Skin Care Review

  6. This is really fascinating, You are an excessively skilled blogger.

    I’ve joined your feed and look forward to in quest of more
    of your wonderful post. Additionally, I have shared your web
    site in my social networks

    Here is my blog … Bio Shed Keto

  7. My family all the time say that I am wasting my time
    here at net, however I know I am getting know-how
    daily by reading thes good articles.

    Here is my web page … http://www.hotelforrest.ru

  8. I do not even know how I stopped up right here, however I
    assumed this publish was once good. I do not realize who you are but certainly you are going to a famous blogger
    in the event you are not already 😉 Cheers!

    Also visit my site: Bio Shed Keto Slim Pills

  9. Generally I do not learn post on blogs, but I would like to
    say that this write-up very compelled me to take a look at
    and do so! Your writing style has been surprised me.
    Thank you, very nice article.

  10. Hi there great blog! Does running a blog such as this
    require a massive amount work? I have no understanding of coding however I had been hoping to start my own blog soon. Anyways, if you have any suggestions or tips for new blog owners
    please share. I know this is off subject but I simply needed to ask.
    Many thanks!

    Visit my web page :: Pure Keto Burn Pills (http://www.koan.at/UserProfile/tabid/61/userId/276555/Default.aspx)

  11. Wonderful items from you, man. I’ve have in mind your stuff prior
    to and you’re simply too wonderful. I really like
    what you’ve acquired here, really like what you are stating and the
    best way during which you assert it. You make it entertaining and you still take care
    of to keep it sensible. I can not wait to learn much more from you.
    That is actually a wonderful site.

  12. You really make it seem so easy with your presentation but I find this topic to be actually something which I
    think I would never understand. It seems too
    complex and very broad for me. I’m looking forward for your next
    post, I will try to get the hang of it!

  13. When someone writes an piece of writing he/she retains the image of a user in his/her brain that how a user can know it.
    Thus that’s why this article is amazing. Thanks!

    my webpage … Optimum Keto Review

  14. It’s an remarkable piece of writing in favor of all
    the web people; they will take benefit from it I am sure.

    Also visit my web site Wawza Apple Cider Vinegar (http://www.hltkd.tw/hl4/userinfo.php?uid=69164)

  15. I cling on to listening to the newscast speak about getting boundless
    online grant applications so I have been looking around for the
    finest site to get one. Could you tell me please, where could i get some?

    my page – Cognitive IQ Review

  16. There is visibly a lot to identify about this. I assume you made
    various nice points in features also.

    my site … Natural Burn Keto Reviews

  17. My spouse and I stumbled over here coming from a different web address and thought I
    should check things out. I like what I see so i am just following you.
    Look forward to exploring your web page again.

  18. This page truly has all the info I wanted concerning this subject and
    didn’t know who to ask.

  19. I am actually thankful to the owner of this web site who has shared this great post at at this time.

  20. I’m really loving the theme/design of your blog. Do you ever run into any web
    browser compatibility issues? A handful of my blog visitors have complained about
    my site not operating correctly in Explorer but looks great in Opera.
    Do you have any solutions to help fix this issue?

  21. I really love your blog.. Pleasant colors & theme.
    Did you create this website yourself? Please reply back as I’m attempting to create my own personal
    site and would like to know where you got this from or just what the theme is named.
    Appreciate it!

    Check out my web site – ustcsv.com

  22. I truly prize your work, Great post.

    Review my blog post: Eagle CBD Reviews

  23. Does your website have a contact page? I’m having trouble
    locating it but, I’d like to shoot you an e-mail.
    I’ve got some creative ideas for your blog you might be interested in hearing.
    Either way, great site and I look forward to seeing it
    improve over time.

    Also visit my webpage; Hyper XXL

  24. This website certainly has all of the info I needed about this subject and didn’t
    know who to ask.

    Review my web-site Cognitive IQ Ingredients

  25. I visited various sites except the audio feature for audio songs present at this website is truly excellent.

    Here is my web-site … Optimum Keto Reviews (Luciana)

  26. Hi, i think that i saw you visited my weblog thus i came to ?return the favor?.I’m attempting to
    find things to improve my site!I suppose its
    ok to use some of your ideas!!

    Stop by my blog post :: Insights CBD Reviews (http://www.hotelforrest.ru)

  27. You’re so interesting! I do not think I’ve truly read anything
    like this before. So nice to find another person with some
    original thoughts on this subject. Really.. thanks for starting
    this up. This site is something that is required on the web, someone with a little originality!

  28. I like this web site very much so much great information.

    Here is my homepage … Infinuity CBD Review

  29. Sweet internet site, super design and style,
    really clean and apply genial.

    Feel free to visit my blog post: Arctic Box AC Reviews

  30. I got what you mean, appreciate it for posting.
    Woh I am thankful to find this website through google.

    Here is my site … Biodermeux

  31. Hi there! This post couldn?t be written much better! Reading through this article reminds me of my previous
    roommate! He continually kept preaching about this.

    I most certainly will send this information to him.
    Fairly certain he will have a great read. Many
    thanks for sharing!

    Here is my webpage … Max BHB

  32. My spouse and i ended up being joyful Albert could round
    up his research from your ideas he made through your web page.
    It’s not at all simplistic just to be releasing guidelines that many many others might have been trying
    to sell. And we also do understand we’ve got the blog owner to appreciate for this.
    The type of explanations you have made, the simple site menu, the relationships you aid to foster –
    it’s got most powerful, and it is letting our son and our family consider that the subject matter
    is amusing, which is extremely essential. Thanks for the whole thing!

    Take a look at my web blog – http://forum.chrisricard.net

  33. I am curious to find out what blog system you have been utilizing?

    I’m experiencing some small security problems with my latest site and I’d like to
    find something more secure. Do you have any suggestions?

    Feel free to visit my website; Viking XL Keto Reviews (http://www.fles.hlc.edu.tw/userinfo.php?uid=1172035)

  34. I conceive you have observed some very interesting details, thank you for the post.

    My website: Niva CBD Gummies Review; vip5.moisait2021.ru,

  35. Wow, amazing weblog format! How long have you been blogging for?

    you made running a blog look easy. The total glance of your site is
    magnificent, let alone the content material!

    Feel free to visit my homepage; Keto Max XR Pills

  36. I enjoy the efforts you have put in this, thanks for all the great posts.

    Feel free to surf to my web blog :: Luiresse Skin Cream

  37. I consider something truly special in this web
    site.

    Stop by my site: http://www.hltkd.tw/

  38. I couldn?t refrain from commenting. Very well written!

    Feel free to surf to my homepage – https://8fx.news

  39. Please let me know if you’re looking for a article writer for your site.
    You have some really good articles and I feel I would
    be a good asset. If you ever want to take some of the
    load off, I’d absolutely love to write some content for your blog in exchange for a link back to mine.
    Please send me an email if interested. Regards!

  40. An impressive share! I’ve just forwarded this onto a friend
    who had been conducting a little homework on this.

    And he actually ordered me lunch simply because I found it for him…
    lol. So let me reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending time to talk
    about this matter here on your internet site.

    Feel free to visit my site: Infinuity CBD (Leonardo)

  41. Keep up the great work, I read few content on this internet
    site and I conceive that your web blog is rattling interesting and contains bands of fantastic information.

    Here is my web-site NeoPodz Review

  42. If some one needs expert view on the topic of
    blogging and site-building after that i propose him/her to visit this weblog, Keep up the fastidious work.

  43. I am regular reader, how are you everybody? This piece of
    writing posted at this web site is in fact good.

  44. Hi, I think your website might be having browser compatibility issues.

    When I look at your blog in Ie, it looks fine but when opening in Internet Explorer, it has some
    overlapping. I just wanted to give you a quick heads up!

    Other then that, amazing blog!

    Look into my web site … Niva CBD Gummies Pri

  45. What i don’t understood is if truth be told how you are not really a lot more well-favored than you
    might be right now. You’re very intelligent. You already know therefore considerably with regards to
    this matter, made me for my part believe it from numerous various angles.

    Its like women and men don’t seem to be fascinated until it’s
    one thing to accomplish with Woman gaga! Your individual stuffs great.
    At all times maintain it up!

    Here is my webpage; Green CBD Gummies Review

  46. It?s nearly impossible to find experienced people in this particular
    subject, however, you seem like you know what you?re talking about!
    Thanks

    My web page; Luiresse Cream

  47. Еverythhing iѕ very opеn with a precise explanation of
    the іssues. It was definitely informative. Your site is useful.
    Many thanks for sharing!

    my paɡe; Bmw dealer near Me

  48. Hello, the whole thing is going fine here and ofcourse every
    one is sharing facts, that’s truly excellent, keep up writing.

    Feel free to surf to my web-site – prettypeople.club

  49. Hey! Someone in my Myspace group shared this website with us so I
    came to look it over. I’m definitely loving the information. I’m book-marking and will be tweeting this to
    my followers! Fantastic blog and terrific
    design.

    My blog – EcoHack Review

  50. Woah! I’m really digging the template/theme of this website.
    It’s simple, yet effective. A lot of times it’s
    hard to get that “perfect balance” between usability and visual appeal.
    I must say you’ve done a awesome job with this. Additionally,
    the blog loads very fast for me on Opera. Exceptional Blog!

  51. I am constantly thought about this, appreciate it for putting up.

    My web-site; Keto Secret Review [forum.adm-tolka.ru]

  52. Hey, you used to write excellent, but the last few posts have been kinda
    boring… I miss your tremendous writings. Past several posts
    are just a bit out of track! come on!

    My web-site … Keto Incinerate Review

  53. What’s up everyone, it’s my first pay a visit at this website, and piece of writing is
    actually fruitful designed for me, keep up posting such posts.

  54. Wonderful blog! Do you have any suggestions for aspiring writers?
    I’m hoping to start my own website soon but I’m a
    little lost on everything. Would you propose starting with a free platform like WordPress
    or go for a paid option? There are so many choices out there that I’m
    completely overwhelmed .. Any tips? Appreciate it!

  55. I rarely create remarks, but after reading a ton of
    remarks on this page Introducción a Document Object Model (DOM) – Java desde 0.
    I actually do have a couple of questions for you if you tend not to mind.
    Is it simply me or do some of the remarks appear like they are
    written by brain dead people? 😛 And, if you are writing at additional social sites, I would like to
    follow anything new you have to post. Would you make a list of all
    of your social pages like your linkedin profile, Facebook page or twitter feed?

    My homepage … Wawza Apple Cider Vinegar Gummies (http://www.vstromturkiye.com/index.php?action=profile;u=84452)

  56. I regard something truly interesting about your web blog so I saved to
    my bookmarks.

    Also visit my website … Total Keto 365 Reviews

  57. Would love to perpetually get updated outstanding site!

    Here is my website – Yec Keto

  58. Undeniably consider that that you stated. Your favourite justification appeared to
    be on the web the easiest factor to have in mind of. I
    say to you, I definitely get annoyed at the same time as folks consider worries that they plainly don’t know about.

    You controlled to hit the nail upon the top and defined out
    the entire thing with no need side-effects , folks could take a signal.
    Will probably be again to get more. Thank you

  59. Hello there, just was aware of your blog thru Google, and found that it is truly informative.
    I am gonna watch out for brussels. I’ll be grateful in case
    you continue this in future. Numerous people will likely be benefited out of your
    writing. Cheers!

    Feel free to visit my web page – ColonBroom

  60. My spouse and I absolutely love your blog and find nearly all of your post’s to be exactly I’m looking for.
    Does one offer guest writers to write content for you?
    I wouldn’t mind producing a post or elaborating on a few
    of the subjects you write related to here. Again, awesome web log!

  61. This web site is my aspiration, very fantastic design and Perfect subject matter.

    Here is my web page … Aizen Power

  62. What’s up, all is going nicely here and ofcourse
    every one is sharing data, that’s really fine, keep up writing.

    Here is my homepage; MaxBHB Reviews

  63. Hey there! I just wanted to ask if you ever have any problems with hackers?
    My last blog (wordpress) was hacked and I ended up losing several
    weeks of hard work due to no backup. Do you have any solutions to prevent hackers?

    Take a look at my web blog Moscatcher

  64. I’m not sure why but this site is loading very slow for me.
    Is anyone else having this problem or is it a problem on my end?
    I’ll check back later on and see if the problem
    still exists.

  65. Hi there, its fastidious post concerning media print, we all be familiar with media is a enormous source of facts.

    My web site – Luiresse Skin

  66. Hi there, everything is going well here and ofcourse every one is sharing information,
    that’s in fact good, keep up writing.

    My webpage Hydrofirm Reviews

  67. Hey! This post couldn’t be written any better! Reading through this post reminds me of my
    previous room mate! He always kept chatting about this.

    I will forward this write-up to him. Pretty sure he will have a good read.
    Many thanks for sharing!

  68. Hi to every one, the contents existing at this site are in fact amazing for people experience, well, keep up the good
    work fellows.

    Feel free to surf to my website; Vigalix Pills

  69. If you are going for most excellent contents like I do,
    simply pay a visit this web site everyday as it presents feature contents, thanks

  70. You got a very great website, Gladiolus I observed
    it through yahoo.

    Feel free to visit my blog – CoolCube AC

  71. Simply want to say your article is as astonishing.
    The clearness on your publish is simply great and i can think you are an expert on this subject.
    Fine with your permission allow me to snatch your feed
    to stay updated with drawing close post. Thank you one
    million and please continue the rewarding work.

    Also visit my website forum.chrisricard.net

  72. Thank you a bunch for sharing this with all folks you actually know what you are talking about!

    Bookmarked. Kindly also discuss with my web site =). We can have
    a hyperlink alternate agreement among us

    Here is my web page: Amellia Skin Cream Reviews

  73. It’s fantastic that you are getting thoughts from this paragraph as well
    as from our dialogue made here.

  74. WOW just what I was searching for. Came here by searching for instagram takipçi satın al

  75. We absolutely love your blog and find many of
    your post’s to be just what I’m looking for. can you offer guest writers to write content in your case?
    I wouldn’t mind writing a post or elaborating on a lot of
    the subjects you write about here. Again, awesome site!

  76. I have read so many articles regarding the blogger lovers except this paragraph is in fact a pleasant article,
    keep it up.

    My web page … ToxyBurn Review

  77. Great post. I’m dealing with a few of these issues as well..

  78. Thanks, I’ve recently been looking for information approximately this topic for ages and yours is the greatest I have came
    upon till now. However, what concerning the conclusion? Are you certain in regards to the supply?

    My site; CBD XLT

  79. Thanks for sharing such a good idea, post is
    pleasant, thats why i have read it completely

    Have a look at my website; Meghan

  80. I enjoy looking at and I conceive this website got some truly useful
    stuff on it!

    Here is my web site – Keto Optimum Review

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

La Ley 34/2002 nos obliga a avisarte de que usamos cookies propias y de terceros con objetivos estadísticos y de sesión y para mostrarte la 'publi' que nos da de comer. Tranquilo, este mensaje solo sale una vez. Más información

Java desde 0 comunica a los usuarios, a través de este aviso, que puede utilizar cookies cuando el usuario navega por las diferentes pantallas y páginas del sitio. Durante el uso de nuestra página Web usted acepta y autoriza expresamente el uso de cookies, de acuerdo con nuestra Política de Privacidad. Este sitio web utiliza las siguientes cookies propias: - Cookies de sesión, para garantizar que los usuarios que escriban comentarios en el blog sean humanos y no aplicaciones automatizadas. De esta forma se combate el spam. Este sitio web utiliza las siguientes cookies de terceros: - Google AdManager y AdSense: Utiliza cookies para mejorar la publicidad. Entre otros fines, suelen utilizarse para segmentarla según el contenido que sea relevante para los usuarios o su ubicación, mejorar los informes de rendimiento de las campañas y evitar mostrar anuncios que los usuarios ya hayan visto. Las cookies no contienen información personal identificable. Consulta cómo utiliza Google la información de sitios web o aplicaciones. y cómo bloquear determinados anuncios. - Google Analytics: Almacena cookies para poder elaborar estadísticas sobre el tráfico y volumen de visitas de esta web. Al utilizar este sitio web está consintiendo el tratamiento de información acerca de usted por Google. Por tanto, el ejercicio de cualquier derecho en este sentido deberá hacerlo comunicando directamente con Google. - Redes sociales: Cada red social utiliza sus propias cookies para que usted pueda pinchar en botones del tipo Me gusta o Compartir.

Cerrar