In this post I would like to share what are the different ways by which we can select a particular DOM element. There are numerous ways of selecting an element, lets focus on the important ways.
Let us consider the following HTML code.
If you have to get the attribute value of myAttribute of the first div with class="myClass"
You can write in two ways -
Let us consider the following HTML code.
<div class="myClass" myAttribute="myAttributeValue">
<span>This is the first span in div </span>
<span class="mySpanClass">This is second span in div </span>
</div>
If you have to get the attribute value of myAttribute of the first div with class="myClass"
You can write in two ways -
One
$("div.myClass").attr('myAttribute');
//output will be myAttributeValue
Two
$(".myClass").attr('myAttribute');
//output will be myAttributeValue
The above second way is not safe if you have elements other than div (such as span,td etc ) with the same class name.Selection by attribute If you want to know the class of the div you can write the following code
$("div[myAttribute=myAttributeValue]").attr('class');
//output will be myClass
One can use, user defined attributes in HTML . For example, <td employee_id=10 > is perfectly valid . If used , user defined attributes provide a lot of information for javascript operations. One should be careful for not exposing sensitive information on the browser(such as passwords) in terms of user defined attributes.Traversing in the DOM If you have select the first span on can write -
One
$("div[myAttribute=myAttributeValue] span").html();
//output will be This is the first span in div
Two
$("div.myClass span").html();
//output will be This is the first span in div
If you have to select the second span in the div, you can write-One
$("div.myClass span.mySpanclass").html();
//output will be This is second span in div
Comments
Post a Comment