Intro to DOM: Study Notes for Ma

作者: 此之木 | 来源:发表于2019-07-04 22:30 被阅读2次

In the last post, I shared my study note about five DOM methods of selecting the element. The next step will be manipulate those selected element. Remember the whole process is select an element and then manipulate.

There are different ways of manipulation:

1. changing an element’s style

2. adding/removing classes

3. changing the content of a tag

4. changing attribute.

Style

The style property is one way to manipulate an element’s style.

I will continue to use the previous HTML page as an example.

var tag = document.getElementById(“highlight”);  //select

tag.style.color = “blue”  //manipulate                                     

tag.style.background = “pink”;  //manipulate

In the example, I select the ID element which corresponds to the first list item. I changed the text color and background by manipulating style in JavaScript. As you see, the text color changes to blue and covers a pink background immediately.

MDN Web Doc recommends for styles to be defined in a separate file or files. The style property allows for quick styling such as testing. 

classList

It is a read-only list that contains the classes for a given element. And it is not an array.

1. add a class: tag.classList.add(“some class”);

2. remove a class: tag.classList.remove(“some class”);

3. toggle a class: tag.classList.toggle(“some class”)

Toggle is very useful. It takes a class name, and if the given element has that class already, it will then remove it. If the element doesn’t have that class then it will turn on.

For example, I create a new class selector on inside style tag named “.big”. And I want to add this “.big” to the h1 tag in the JavaScript. This will make the h1 text in pink and cover in yellow background.

I select the h1 element by using querySelector, and then I add “big” to the class.by writing h1.classList.add(“big”). The result shows the changes immediately. You can try remove and toggle by yourself.

Text Content

It returns a string of all the text contained in a given element.

For example, if I want to change the h2 text content. All I need to do is:

var h2 = document.querySelector(“h2”); //select the element

h2.textContent; //retrive the text content

h2.textContent = “Some Practices”;//alter the text content

As you can see, the h2 text content has changes from “Practices” to “Some Practices”.

Attributes

We use getAttribute() and setAttribute() to read and write attribute like src or href.

In this HTML example, I don’t have any src or href attributes. The basic concepts are:

If we want to change a link, we can write:

var link = document.querySelector(“a”);

link.getAttribute(“href”);

link.setAttribute(“href”,”www.xxx.com”);

相关文章

网友评论

    本文标题:Intro to DOM: Study Notes for Ma

    本文链接:https://www.haomeiwen.com/subject/zxdjaqtx.html