How to identify the HTML element in which a js script is contained?

Asked

Viewed 717 times

-1

Like this: I put a js script inside a div, for example. How can I make this script identify the DIV in which it is contained without selectors like ID or Class?

It’s just that I see some embed scripts that insert things (images, videos, etc.) into the element in which they are placed, without using selectors. How is it done?

NOTE: Javascript pure. I’m learning pure js.

Thank you and good afternoon to all.

  • But the div has an ID ?

  • Can you give an example of the code you refer to to to understand better what you refer to? "I see some embed scripts that insert things [...] inside the element in which they are placed"

2 answers

1

If you do not want to recover by Id or Class. You can recover by Tagname.

document.getElementsByTagName

In the example below, I created a <Li> and also created a <span> to add the recovered value via javascript.

<!DOCTYPE html>
<html>
<body>

<p>Bebidas</p>
<ul>
  <li>Coca Cola</li>
  <li>Pepsi</li>
  <li>Fanta</li>
</ul>

<button onclick="minhaFuncao()">Clique Aqui</button>

<span></span>

<script>
function minhaFuncao() {
    var li = document.getElementsByTagName("li");
    var span = document.getElementsByTagName("span");
    span.innerHTML = li[1].innerHTML;
}
</script>

</body>
</html>

0

You can pass the element by parameter using the command this.

Example:

function teste(elemento) { ... } 

next:

<div onclick="teste(this);"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.