Function to show the element id of a page in a <span id="span"></span>

Asked

Viewed 273 times

0

Javascript must be with event onmouseover

function mostrarID() {
.........................
.........................
}
document.onmouseover = mostrarID;

HTML example

O ID é:"<span id="span" style="font-weight:bold"></span>"<br>
<p id="p1">Paragrafo</p>
<div id="Div1">
<p id="p2">Paragrafo2</p>
<hr id="hr1">
<a href="#" id="Home">Home</a>
</div>
<p id="p3">Paragrafo3</p>
<a href="#" id="nav-questions">Perguntas</a>
<p id="p4">Paragrafo4</p>
<a href="#" id="Tags">Tags</a>

<div id="Div2">
<form id="Form">
<input id="Input" type="text"/>
</form>
</div>

1 answer

0


Just look for the attribute id of the element in question with event.target.getAttribute and set the value in span desired.

const span = document.getElementById("span");

document.onmouseover = function (event) {
  span.innerHTML = event.target.getAttribute("id");
}
O ID é:"<span id="span" style="font-weight:bold"></span>"<br>
<p id="p1">Paragrafo</p>
<div id="Div1">
  <p id="p2">Paragrafo2</p>
  <hr id="hr1">
  <a href="#" id="Home">Home</a>
</div>
<p id="p3">Paragrafo3</p>
<a href="#" id="nav-questions">Perguntas</a>
<p id="p4">Paragrafo4</p>
<a href="#" id="Tags">Tags</a>

<div id="Div2">
  <form id="Form">
    <input id="Input" type="text" />
  </form>
</div>

  • Why does it only work if you put the script below html? I never understood it.

  • Execution order in the browser. If placed before, the element #span will not exist in the GIFT when getElementById("span") is executed, keeping as null the variable span. Confirm this by accessing the browser console, the error probably appeared Cannot set Property 'innerHTML' of null .

  • Thanks Anderson Carlos Woss

  • Perfect, I tested on all five browsers! I was using var elem = Document.elementFromPoint(Event.clientX, Event.clientY) Document.all.span.innerText = elem.id but firefox does not work.

Browser other questions tagged

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