The example in this article describes how JQuery finds DOM nodes. Share it with everyone for your reference. The specific analysis is as follows:
DOM operations are the most common usage of JQuery. Let’s analyze JQuery’s DOM operations one by one. Let’s start with the simplest node search operation.
In order to comprehensively explain DOM operations, you first need to build a web page. Because every web page can be represented by DOM, and every DOM can be regarded as a DOM tree. The HTML code is as follows:
<p class="nm_p" title="欢迎访问脚本之家" >欢迎访问脚本之家</p> <ul class="nm_ul"> <li title='PHP编程'>简单易懂的PHP编程</li> <li title='JavaScript编程'>简单易懂的JavaScript编程</li> <li title='JQuery编程'>简单易懂的JQuery编程</li> </ul>
By the way, nm in the class name is the abbreviation of nowamagic~
Finding nodes on the document tree is very easy using JQuery and can be done through JQuery selectors.
Find element node
Get the element node and print out its text content. The JQuery code is as follows:
var $li = $(".nm_ul li:eq(1)"); // 获取第二个<li>元素节点 var li_txt = $li.text(); // 输出第二个<li>元素节点的text
The above code obtains the second
Find attribute node
After using the JQuery selector to find the required element, you can use the attr() method to obtain the values of its various attributes. The parameter of the attr() method can be one or two. When the parameter is one, it is the name of the attribute to be queried, for example:
Get the attribute node and print out its text content. The JQuery code is as follows:
var $para = $(".nm_p"); // 获取<p>节点 var p_txt = $para.attr("title"); // 输出<p>元素节点属性title
The above code obtains the
node with class nm_p and prints out the value of its title attribute "Welcome to the Concise Modern Magic Library".
The complete JQuery code for this example is as follows:
<script type="text/javascript"> //<![CDATA[ $(function(){ var $para = $(".nm_p"); // 获取<p>节点 var $li = $(".nm_ul li:eq(1)"); // 获取第二个<li>元素节点 var p_txt = $para.attr("title"); // 输出<p>元素节点属性title var ul_txt = $li.attr("title"); // 获取<ul>里的第二个<li>元素节点的属性title var li_txt = $li.text(); // 输出第二个<li>元素节点的text $("#btn_1").click(function(){ alert(ul_txt); }); $("#btn_2").click(function(){ alert(li_txt); }); $("#btn_3").click(function(){ alert(p_txt); }); }); //]]> </script>
I hope this article will be helpful to everyone’s jQuery programming.