Truy cập các phần tử DOM

jQuery hỗ trợ các phương thức truy cập các phần tử trong trang web sau: theo ID, theo tên thẻ HTML, theo thuộc tính HTML, theo tên CSS, theo XPath.

1. Thông qua ID
Cú pháp truy cập phần tử DOM theo ID có dạng: $('#ID'). Thí dụ 1, ẩn phần tử DOM có ID là 'MyID':

  1. <script>
  2. <!--
  3. $(function(){
  4. $('#MyID').hide();
  5. });
  6. -->
  7. </script>

2. Thông qua tên thẻ HTML
Cú pháp truy cập phần tử DOM theo thẻ HTML có dạng: $('tagName'). Thí dụ 2, ẩn tất cả các phần tử DOM có tên thẻ 'p':

  1. <script>
  2. <!--
  3. $(function(){
  4. $('p').hide();
  5. });
  6. -->
  7. </script>

Thí dụ 3, ẩn phần tử DOM đầu tiên có tên thẻ là 'DIV':

  1. <script>
  2. <!--
  3. $(function(){
  4. $('p:eq(0)').hide();
  5. });
  6. -->
  7. </script>

3. Thông qua thuộc tính HTML
Cú pháp truy cập phần tử DOM theo thuộc tính HTML có dạng $('[@key=@val]'). Thí dụ 4, chọn lựa các phần tử DOM có tên thẻ là 'input' và thuộc tính 'type' là 'hidden', sau đó, thay đổi giá trị của các phần tử đó thành 'I am a hidden field':

  1. <script>
  2. <!--
  3. $(function(){
  4. $('input[@type=hidden]').each(function(){
  5. $(this).val('I am a hidden field');
  6. });
  7. });
  8. -->
  9. </script>

Kỳ tới:
4. Truy cập phần DOM theo phương thức XPath
5. Truy cập phần DOM theo phương thức CSS
6. Các phương thức truy cập đặc biệt

Thế Hồng,

Tham khảo:
1. JQuery docs

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <sup> <br> <p> <h3>
  • Lines and paragraphs break automatically.
  • Link to content with [[some text]], where "some text" is the title of existing content or the title of a new piece of content to create. You can also link text to a different title by using [[link to this title|show this text]]. Link to outside URLs with [[http://www.example.com|some text]], or even [[http://www.example.com]].
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.