Kardinata Kardinata - 19 days ago 6
Javascript Question

Why return getElementsBy** not working?

HTML:

<ul id="ul-id">
<li>Text Content</li>
<li>Text Content</li>
<li>Text Content</li>
<li>Text Content</li>
</ul>




Javascript:

function getId(idname) {return document.getElementById(idname);} // with document at first


function getTag(tagname) {return getElementsByTagName(tagname);} // witout document at first




Results:

When i call it with:

getId("ul-id").innerHTML // this code is working fine 


getId("ul-id").getTag("li").length // not working


document.getElementById("ul-id").getTag("li").length // this also not working


Can you tell me the reason and how to fix it ? ^_^

Answer

If you really want to add a custom method on elements in the DOM, you need to extend the Element prototype to add the method.

In that case the method chaining works as follows:

function getId(idname) {
  return document.getElementById(idname);
}

Element.prototype.getTags = function getNestedElements(tagName) {
  return this.getElementsByTagName(tagName);
};


Element.prototype.getTag = function getNestedElements(tagName) {
  return this.getTag(tagName)[0];
};


document.write(
  getId('ul-id').getTags('li').length
);
<ul id="ul-id">
  <li>Text Content</li>  
  <li>Text Content</li>  
  <li>Text Content</li>  
  <li>Text Content</li>  
</ul>