CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2009
    Posts
    20

    javascript - need suggestions with getting specific elements from container

    hi,
    here is what i want to do:

    e.g.
    Code:
    <div id="container">
    	<h1>text</h1>
    	<p>text</p>
    	<p>text</p>
    	<p>text</p>
    	<p>text</p>
    	<p>text</p>
    	<random tag></<random tag>>
    	.
    	.
    	.
    	<h1>text</h1>
    	<p>text</p>
    	<p>text</p>
    	.
    	.
    	.
    </div>
    i want to get list of all h1 and p, but i need to preserve order e.g h1pppppppph1ppppph1pp,
    i can do this by getting all elements and then check if element.tagName == "h1" but this way i will check hundreds of elements that i dont need while getting only few h1 and p, is there a way to optimize it, or maybe better approach ?

  2. #2
    Join Date
    May 2002
    Posts
    10,943

    Re: javascript - need suggestions with getting specific elements from container

    You are correct about the method, but I think you are confused as to how easy, and few lines of code, it is.

    Code:
    var output = "";
    var elms = document.getElementsByTagName("*");
    for (var i = 0; i < elms.length; i++) {
      if (elms[i].tagName == "h1") {output += "h1"}
      if (elms[i].tagName == "p") {output += "p"}
    }
    alert(output);
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  3. #3
    Join Date
    Aug 2009
    Posts
    20

    Re: javascript - need suggestions with getting specific elements from container

    first and last optimization - skip some for loop iterations -when i am sure i wont omit h1 or p - DONE

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured