Get the variable id that contains a label to

1

I'm trying to get through JS the id that has a tag. The id is going to vary, so when doing onClick I have to know it.

<a href="#" role="button" onClick="abrirNoticia();" id="id">Título</a>

As for the function, I was using the following code but the truth is that I'm a little lost:

function abrirNoticia(element){
  var parent = element.parentNode;
  alert(parent.id);
  var content = parent.querySelector("a");
  alert(content.id);
}
    
asked by Adry Dam 18.07.2017 в 20:21
source

3 answers

1

In its function, the problem is that it receives a undefined since it does not send a value associated to the parameter element . from HTML you should pass this that refers to the element.

function abrirNoticia(element){
  alert(element.id);
}
<a href="#" role="button" onClick="abrirNoticia(this);" id="id22">Título</a>

If you want to get the id of any element a of the document, you can assign the event to all those that exist.

var content = document.querySelectorAll("a");
for (var i = 0; i <content.length; i++) {
content[i].addEventListener("click",function(){
alert(this.id);
})
}
<a href="#" role="button"  id="id">Título</a>
<a href="#" role="button"  id="id1">Título1</a>
<a href="#" role="button"  id="id2">Título2</a>
    
answered by 18.07.2017 / 20:30
source
2

Try sending the element itself as a parameter to the function using this :

function abrirNoticia(elemento)
{
 alert(elemento.id);
}
<a href="#" role="button" onClick="abrirNoticia(this);" id="id-aleatorio">Título</a>
    
answered by 18.07.2017 в 20:26
0

I'm guessing that the links are created dynamically in the loading of the page. There are a couple of ways you can do that. One is to go directly into the id, Like:

AbrirNoticia (7) 

or use "this" as:

AbrirNoticia (this) and reference it in javascript as element.id

    
answered by 18.07.2017 в 20:28