During our development process, I believe everyone knows that the getAttribute() method in JavaScript is a function, and getAttribute() has only one parameter - what you plan to query The name of attribute, today we will introduce to you the use of getAttribute in JavaScript!
getAttribute() method
So far, we have introduced to you two methods of retrieving specific element nodes: one is to use the getElementById() method, and the other is to The first is to use the getElementsByTagName() method. After finding that element, we can use the getAttribute() method to query the values of its various attributes.
getAttribute() method is a function. It has only one parameter - the name of the attribute you intend to query:
object.getAttribute(attribute)
However, the getAttribute() method cannot be called through the document object, which is different from what we introduced before The other methods are different. We can only call it through an element node object.
For example, you can combine it with the getElementsByTagName() method to query the title attribute of each
element, as shown below:
var text=document.getElementsByTagName("p") for (var i=0;i<text.length;i++) { alert(text[i].getAttribute("title")); }
If you insert the above code in front At the end of the "Shopping List" example document given and reloading the page in your web browser, an alter dialog box will pop up on the screen with the text message "a gentle reminder".
There is only one
element with a title attribute in the "Shopping List" document. If this document also has one or more
elements without a title attribute, the corresponding getAttribute("title") call will return null. null is the null value in the JavaScript language, which means "the thing you are talking about does not exist." If you want to verify this for yourself, first insert the following text into the Shopping List document after the existing text paragraph:
<p>This is just test</p>
Then reload the page. This time, you will see two alter dialog boxes, and the second dialog box will be blank or just display the word "null" - depending on how your web browser displays null values.
We can modify our script so that it only pops up a message when the title attribute exists. We will add an if statement to check if the return value of the getAttribute() method is null. Taking this opportunity, we also added a few variables to improve the readability of the script:
var ts=document.getElementsByTagName("li"); for (var i=0; i<ts.length;i++) {text=ts[i].getAttribute("title"); if(text!=null) { alert(text) } }
Now, if you reload this page, you will only see a message saying "a gentle reminder" The alter dialog box is shown below.
We can even make this code shorter. When checking whether an item of data is null, we are actually checking whether it exists. This check can be simplified by directly using the data being checked as the condition of the if statement. if (something) is completely equivalent to if (something != null), but the former is obviously more concise. At this point, if something exists, the condition of the if statement will be true; if something does not exist, the condition of the if statement will be false.
Specifically for this example, as long as we replace if (title_text != null) with if (title_text), we can get a more concise code. In addition, in order to further increase the readability of the code, we can also take this opportunity to write the alter statement and the if statement on the same line, which can make them closer to the English sentences in our daily life:
var ts=document.getElementsByTagName("li"); for (var i=0; i<ts.length;i++) {text=ts[i].getAttribute("title"); if(text) alert(text) }
3.4.2 SetAttribute() method
All the methods we introduced to you before can only be used to retrieve information. The setAttribute() method has one essential difference from them: it allows us to modify the value of the attribute node.
Similar to the getAttribute() method, the setAttribute() method is also a function that can only be called through the element node object, but the setAttribute() method requires us to pass two parameters to it:
obiect.setAttribute(attribute,value )
In the following example, the first statement will retrieve the element whose id attribute value is purchase, and the second statement will set the title attribute value of this element to a list of goods:
var shopping=document.getElementById("purchases") shopping.setAttribute("title","a list of goods")
We can use the getAttribute() method to prove that the value of the title attribute of this element has indeed changed:
var shopping=document.getElementById("purchases"); alert(shopping.getAttribute("title")); shopping.setAttribute("title","a list of goods"); alert(shopping.getAttribute("title"));
上面这些语句将在屏幕上弹出两个alert对话框:第一个alter对话框出现在setAttribute()方法被调用之前,它将是一片空白或显示着单词“null”;第二个出现在title属性值被设置之后,它将显示着“a list of goods”消息。
在上例中,我们设置了一个现有节点的title属性,但这个属性原先并不存在。这意味着我们发出的setAttribute()调用实际完成了两项操作:先把这个属性创建出来,然后再对其值进行设置。如果我们把setAttribute()方法用在元素节点的某个现有属性上,这个属性的当前值将被覆盖。
在“购物清单”示例文档里,
元素已经有了一个title属性,这个属性的值是a gentle reminder。我们可以用setAttribute()方法来改变它的当前值:
<script type="text/javascript"> var ts=document.getElementsByTagName("li"); for (var i=0; i<ts.length;i++) { var text=ts[i].getAttribute("title"); alert(ts[i].getAttribute("title")) if(text) { ts[i].setAttribute("title","我会成功!") alert(ts[i].getAttribute("title")) } }
上面这段代码将先从文档里把已经带有title属性的
元素全部检索出来,然后把它们的title属性值全部修改为brand new title text。具体到“购物清单”文档,属性值a gentle reminder将被覆盖。
这里有一个非常值得关注的细节:通过setAttribute()方法对文档做出的修改,将使得文档在浏览器窗口里的显示效果和/或行为动作发生相应的变化,但我们在通过浏览器的view source(查看源代码)选项去查看文档的源代码时看到的仍将是原来的属性值——也就是说,setAttribute()方法做出的修改不会反映在文档本身的源代码里。这种“表里不一”的现象源自DOM的工作模式:先加载文档的静态内容、再以动态方式对它们进行刷新,动态刷新不影响文档的静态内容。这正是DOM的真正威力和诱人之处:对页面内容的刷新不需要最终用户在他们的浏览器里执行页面刷新操作就可以实现。
总结:
相信小伙伴们通过本文的认真学习以后,对JavaScript中getAttribute的使用有了进一步的了解和认识,希望通过本文介绍对你的工作有所帮助!
相关推荐:
javascript setAttribute, getAttribute 在不同浏览器上的不同表现
js中 aaa.style 和 aaa.getAttribute('style') 等价吗,有无区别?
有趣的script标签用getAttribute方法来自脚本吧
The above is the detailed content of Introduction to the use of getAttribute in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
