How to call your own method using "this" in the DOM node

I would like to do something like this:

function alrtHtml() {
  alert(this.innerHTML)
}

function myFunc(id) {
  document.getElementById(id).alrtHtml()
}
<html>
<head>
  <meta charset="UTF-8" />
  <title>test</title>
</head>
<body>
  <h1 id="h1">Hallo world!</h1>
  <input type="button" value="click" onclick="myFunc('h1')" >
</body>
</html>
Run codeHide result

Must warn the text "Hallo world!" inside the tag h1.

+4
source share
3 answers

What you want to do is add your function to any type prototypedocument.getElementById(id) .

In this case, it returns Element, therefore, to add your function to your prototype, you must write the following code.

Element.prototype.alrtHtml = function() {
  alert(this.innerHTML)
}
+4
source

, , - , innerHTML, .

, -

function getElement(selector) {
  if (!(this instanceof getElement)) return new getElement(selector);
  this.element = document.querySelector(selector);
  return this;
}

getElement.prototype.alertHtml = function() {
  alert(this.element.innerHTML);
  return this;
}

function myFunc(id) {
  getElement(id).alertHtml();
}

myFunc('#test');
<div id="test">TEST</div>
Hide result

, , , .

+4

alertHTML:

function alertHTML(el) {
  alert(el.innerHTML)
}

function myFunc(id) {
  var elArg = document.getElementById(id)
  alertHTML(elArg)
  
  // You could also write it like this:
  /*
  alertHTML(document.getElementById('h1'))
  */
}
<h1 id='h1'>Hello, world</h1>
<button onclick="myFunc('h1')">Button</button>
Hide result

, , , - alertHTML Element.

EDIT: If you really want to use this, you might also like to learn about binding functions - funfunfunction made a nice video on this here . Here's how it will work:

function alertHTML() {
  alert(this.innerHTML)
}

function myFunc(id) {
  var el = document.getElementById(id)
  alertHTML.apply(el)
}
<h1 id='h1'>Hello, world</h1>
<button onclick="myFunc('h1')">Button</button>
Run codeHide result

applyruns its function with thisas the first argument that you pass apply. (The remaining arguments passed in applyare passed directly to the function.)

0
source

Source: https://habr.com/ru/post/1659643/


All Articles