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

-1

So: 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?

I see some embedding scripts that insert things (images, videos and etc) into the element they are placed in, without having to use selectors. How is this done?

OBS: Pure Javascript. I'm learning pure js.

Thank you and good afternoon to all.

    
asked by anonymous 23.10.2016 / 20:09

2 answers

1

If you do not want to recover by Id or Class. You can retrieve it by TagName.

document.getElementsByTagName

In the example below, I created a <Li> of drinks and also created a <span> to add the value retrieved 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>
    
23.10.2016 / 20:29
0

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

Example:

function teste(elemento) { ... } 

then:

<div onclick="teste(this);"></div>
    
23.10.2016 / 21:43