Jquery Find Existing Element on Page and Append It Again

Introduction

In the previous tutorial in this series, "How To Make Changes to the DOM," we covered how to create, insert, replace, and remove elements from the Document Object Model (DOM) with built-in methods. By increasing your proficiency in manipulating the DOM, you are meliorate able to utilize JavaScript's interactive capabilities and modify web elements.

In this tutorial, we volition acquire how to further alter the DOM by modifying styles, classes, and other attributes of HTML element nodes. This will requite you a greater understanding of how to manipulate essential elements within the DOM.

Review of Selecting Elements

Until recently, a popular JavaScript library chosen jQuery was virtually often used to select and modify elements in the DOM. jQuery simplified the process of selecting one or more elements and applying changes to all of them at the same time. In "How To Access Elements in the DOM," we reviewed the DOM methods for grabbing and working with nodes in vanilla JavaScript.

To review, certificate.querySelector() and document.getElementById() are the methods that are used to admission a single element. Using a div with an id attribute in the example below, we can access that element either way.

                                                    <div              id                              =                "demo-id"                            >            Demo ID                              </div              >                              

The querySelector() method is more robust in that it can select an element on the page by whatsoever type of selector.

                      // Both methods volition return a single element            const            demoId            =            document.            querySelector            (            '#demo-id'            )            ;                  

Accessing a single element, we can hands update a function of the chemical element such as the text inside.

                      // Change the text of i chemical element            demoId.textContent            =            'Demo ID text updated.'            ;                  

However, when accessing multiple elements by a mutual selector, such as a specific course, nosotros take to loop through all the elements in the list. In the code below, we have 2 div elements with a mutual grade value.

                                                    <div              grade                              =                "demo-class"                            >            Demo Class one                              </div              >                                                      <div              course                              =                "demo-course"                            >            Demo Class 2                              </div              >                              

We'll use querySelectorAll() to grab all elements with demo-class applied to them, and forEach() to loop through them and utilize a change. It is also possible to access a specific element with querySelectorAll() the same mode y'all would with an assortment — by using bracket notation.

                      // Get a NodeList of all .demo elements            const            demoClasses            =            document.            querySelectorAll            (            '.demo-class'            )            ;            // Change the text of multiple elements with a loop            demoClasses.            forEach            (            element            =>            {            chemical element.textContent            =            'All demo classes updated.'            ;            }            )            ;            // Access the first element in the NodeList            demoClasses[            0            ]            ;                  

This is ane of the near important differences to exist aware of when progressing from jQuery to vanilla JavaScript. Many examples of modifying elements will not explain the process of applying those methods and properties to multiple elements.

The properties and methods in this article will often be attached to consequence listeners in order to answer to clicks, hovers, or other triggers.

Note: The methods getElementsByClassName() and getElementsByTagName() will render HTML collections which do non have admission to the forEach() method that querySelectorAll() has. In these cases, yous will need to use a standard for loop to iterate through the collection.

Modifying Attributes

Attributes are values that contain boosted information almost HTML elements. They usually come in proper noun/value pairs, and may be essential depending on the element.

Some of the most mutual HTML attributes are the src aspect of an img tag, the href of an a tag, course, id, and fashion. For a total list of HTML attributes, view the attribute list on the Mozilla Developer Network. Custom elements that are not role of the HTML standard will be prepended with data-.

In JavaScript, we have four methods for modifying element attributes:

Method Description Example
hasAttribute() Returns a truthful or false boolean element.hasAttribute('href');
getAttribute() Returns the value of a specified attribute or cipher element.getAttribute('href');
setAttribute() Adds or updates value of a specified attribute element.setAttribute('href', 'alphabetize.html');
removeAttribute() Removes an attribute from an element chemical element.removeAttribute('href');

Permit'due south create a new HTML file with an img tag with i attribute. We'll link to a public image available via a URL, but you lot can bandy it out for an alternate local image if yous're working offline.

attributes.html

                                    <!              DOCTYPE              html              >                                                      <html              lang                              =                "en"                            >                                                      <trunk              >                                                      <img              src                              =                "https://js-tutorials.nyc3.digitaloceanspaces.com/shark.png"                            >                                                      </body              >                                                      </html              >                              

When you load the above HTML file into a modern web browser and open the built-in Developer Panel, y'all should see something similar this:

First rendering of classes.html

Now, we tin exam all the attribute methods on the wing.

                      // Assign image element            const            img            =            document.            querySelector            (            'img'            )            ;            img.            hasAttribute            (            'src'            )            ;            // returns true            img.            getAttribute            (            'src'            )            ;            // returns "...shark.png"            img.            removeAttribute            (            'src'            )            ;            // remove the src aspect and value                  

At this signal, yous volition have removed the src aspect and value associated with img, merely yous can reset that attribute and assign the value to an alternate image with img.setAttribute():

          img.            setAttribute            (            'src'            ,            'https://js-tutorials.nyc3.digitaloceanspaces.com/octopus.png'            )            ;                  

Second rendering of classes.html

Finally, we can modify the attribute direct by assigning a new value to the attribute as a property of the chemical element, setting the src dorsum to the shark.png file

          img.src            =            'https://js-tutorials.nyc3.digitaloceanspaces.com/shark.png'            ;                  

Whatsoever aspect tin can be edited this mode as well as with the higher up methods.

The hasAttribute() and getAttribute() methods are usually used with conditional statements, and the setAttribute() and removeAttribute() methods are used to directly modify the DOM.

Modifying Classes

The form attribute corresponds to CSS class selectors. This is not to be confused with ES6 classes, a special type of JavaScript function.

CSS classes are used to apply styles to multiple elements, unlike IDs which tin can only exist once per folio. In JavaScript, nosotros have the className and classList properties to work with the class attribute.

Method/Holding Description Example
className Gets or sets class value chemical element.className;
classList.add together() Adds ane or more grade values element.classList.add('active');
classList.toggle() Toggles a class on or off element.classList.toggle('active');
classList.contains() Checks if class value exists chemical element.classList.contains('active');
classList.replace() Replace an existing class value with a new form value chemical element.classList.supplant('old', 'new');
classList.remove() Remove a course value element.classList.remove('agile');

Nosotros'll make some other HTML file to work with the form methods, with ii elements and a few classes.

classes.html

                                    <!              DOCTYPE              html              >                                                      <html              lang                              =                "en"                            >                                                      <style              >                                                      body                {                max-width                :                600px;                margin                :                0 auto;                font-family unit                :                sans-serif;                }                .active                {                border                :                2px solid blue;                }                .warning                {                edge                :                2px solid red;                }                .hidden                {                display                :                none;                }                div                {                edge                :                2px dashed lightgray;                padding                :                15px;                margin                :                5px;                }                                                                    </style              >                                                      <body              >                                                      <div              >            Div 1                              </div              >                                                      <div              course                              =                "active"                            >            Div 2                              </div              >                                                      </body              >                                                      </html              >                              

When you open the classes.html file into a web browser, you should receive a rendering that looks similar to the following:

First rendering of classes.html

The className belongings was introduced to prevent conflicts with the class keyword found in JavaScript and other languages that have access to the DOM. Yous can utilise className to assign a value straight to the class.

                      // Select the first div            const            div            =            document.            querySelector            (            'div'            )            ;            // Assign the alarm class to the commencement div            div.className            =            'warning'            ;                  

We take assigned the alarm grade defined in the CSS values of classes.html to the first div. You'll receive the following output:

Second rendering of classes.html

Annotation that if any classes already exist on the element, this will override them. You can add multiple infinite delimited classes using the className property, or use information technology without consignment operators to go the value of the class on the chemical element.

The other fashion to modify classes is via the classList property, which comes with a few helpful methods. These methods are similar to the jQuery addClass, removeClass, and toggleClass methods.

                      // Select the second div by class name            const            activeDiv            =            document.            querySelector            (            '.active'            )            ;            activeDiv.classList.            add together            (            'hidden'            )            ;            // Add the hidden grade            activeDiv.classList.            remove            (            'hidden'            )            ;            // Remove the hidden grade            activeDiv.classList.            toggle            (            'hidden'            )            ;            // Switch betwixt hidden true and false            activeDiv.classList.            replace            (            'active'            ,            'warning'            )            ;            // Supersede active grade with warning class                  

After performing the above methods, your web page volition look similar this:

Final rendering of classes.html

Unlike in the className case, using classList.add() will add together a new class to the list of existing classes. You lot can also add multiple classes as comma-separated strings. It is also possible to use setAttribute to modify the class of an element.

Modifying Styles

The style property represents the inline styles on an HTML element. Often, styles will exist practical to elements via a stylesheet equally we have washed previously in this article, but sometimes we have to add or edit an inline fashion directly.

We will make a short instance to demonstrate editing styles with JavaScript. Below is a new HTML file with a div that has some inline styles applied to display a foursquare.

styles.html

                                    <!              DOCTYPE              html              >                                                      <html              lang                              =                "en"                            >                                                      <body              >                                                      <div                              style                                  =                  "                                      acme                    :                    100px;                    width                    :                    100px;                    edge                    :                    2px solid black;                                    "                                            >            Div                              </div              >                                                      </body              >                                                      </html              >                              

When opened in a spider web browser, the styles.html will wait something similar this:

First rendering of styles.html

I option to edit the styles is with setAttribute().

                      // Select div            const            div            =            document.            querySelector            (            'div'            )            ;            // Apply style to div            div.            setAttribute            (            'style'            ,            'text-marshal: middle'            )            ;                  

All the same, this will remove all existing inline styles from the element. Since this is likely not the intended effect, information technology is ameliorate to use the style attribute directly

          div.manner.height            =            '100px'            ;            div.way.width            =            '100px'            ;            div.style.border            =            '2px solid black'            ;                  

CSS backdrop are written in kebab-case, which is lowercase words separated by dashes. It is important to annotation that kebab-instance CSS properties cannot be used on the JavaScript way property. Instead, they volition be replaced with their camelCase equivalent, which is when the beginning give-and-take is lowercase, and all subsequent words are capitalized. In other words, instead of text-marshal we will use textAlign for the JavaScript style property.

                      // Make div into a circle and vertically center the text            div.style.borderRadius            =            'l%'            ;            div.mode.display            =            'flex'            ;            div.style.justifyContent            =            'eye'            ;            div.style.alignItems            =            'center'            ;                  

Later completing the above style modifications, your concluding rendering of styles.html volition show a circumvolve:

Final rendering of styles.html

If many stylistic changes are to be applied to an element, the all-time course of activity is to apply the styles to a grade and add a new form. Even so, there are some cases in which modifying the inline style attribute will be necessary or more straightforward.

Conclusion

HTML elements often take additional information assigned to them in the form of attributes. Attributes may consist of proper noun/value pairs, and a few of the most mutual attributes are class and manner.

In this tutorial, nosotros learned how to access, modify, and remove attributes on an HTML element in the DOM using manifestly JavaScript. We also learned how to add together, remove, toggle, and supercede CSS classes on an element, and how to edit inline CSS styles. For additional reading, check out the documentation on attributes on the Mozilla Developer Network.

smithforneve.blogspot.com

Source: https://www.digitalocean.com/community/tutorials/how-to-modify-attributes-classes-and-styles-in-the-dom

0 Response to "Jquery Find Existing Element on Page and Append It Again"

Enviar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel