Skip to content Skip to sidebar Skip to footer

Iterate Over Dom Elements Using Document.getelementsbytagname, Pass Element As Jquery Object

What I need is to iterate over the dom at some start element and then go through all elements below the start element. Here is what I was doing so far. function iterDomFromStartEle

Solution 1:

Preface: I think you're better off fixing the problem properly. You might save an hour or two now by taking a shortcut, but it's likely to cost you in the long term.

But re your actual question:

how can I convert the items[i] into a jquery object so that in my call back function, I can do node.css(......)?

If you pass a raw DOM object into $(), jQuery will return a wrapper around it. You don't have to go via the ID.

You can also get a jQuery instance for all descendant elements of a given starting point, like this:

var x = $("#starting_point *");

...although you'd still end up creating a lot of temporary objects if you then looped through it, like this:

$("#starting_point *").each(function() {
    // Here, `this` is the raw DOM element
});

Here's an example of looping all elements under a given starting point with jQuery, in this case showing their tag and id (if any) and turning them blue (live copy):

$("#start *").each(function() {
  display(this.tagName + "#" + (this.id || "?"));
  $(this).css("color", "blue");
});

Note I said under. If you also want to include #start, the selector changes to #start, #start *.

Here's a complete example of increasing the font size of elements starting with (and including) a given start point, where the font size is variously set by inline and stylesheet styles (live copy):

CSS:

.x13 {
  font-size: 13px;
}
.x17 {
  font-size: 17px;
}
.x20 {
  font-size: 20px;
}

HTML:

<inputtype="button"id="btnBigger"value="Bigger"><divid="start"class="x13">
  This is in 13px
  <pstyle="font-size: 15px">This is in 15px
    <spanclass="x17">and this is 17px</span></p><ul><liid="the_list_item"style="10px">10px
      <strongstyle="font-size: 8px">8px
        <emclass="x20">five</em></strong></li></ul></div>

JavaScript:

jQuery(function($) {

  $("#btnBigger").click(function() {
    $("#start, #start *").each(function() {
      var $this = $(this),
          fontSize = parseInt($this.css("font-size"), 10);
      display("fontSize = " + fontSize);
      $this.css("font-size", (fontSize + 2) + "px");
    });
  });

  functiondisplay(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }

});

Post a Comment for "Iterate Over Dom Elements Using Document.getelementsbytagname, Pass Element As Jquery Object"