How to get selected item with click (id and position)

1

I'm trying to do some things with DOM and I have a problem that, a priori, I find no solution.

Given an HTML code, I would like to obtain the type of element (div, button, table ...) and its position.

Obtaining the type of element with the target is easy, its position not so much.

I give an example:

If I click on this list "Coffe", with the target I get "LI" which is the object of Coffe, even there perfect, but how can I work with that LI object in particular? I mean, how can I, for example, modify its content?

Because to modify its content I have several options:

  • document.getElementsByTagName ("tag") [position]: And of course I do not have the position.
  • document.getElementById ("id"). innerHTML: I'm working with html without id's.

Any ideas? Should I necessarily put id's? I think it's late.

Thank you very much again.

  if (e.srcElement){
	  tag = e.srcElement.tagName;
  }else{ (e.target)
  	  tag = e.target.type;
  }
 
  console.log("El elemento selecionado ha sido " + tag);
	<ul> <!-- Primer ul -->
		  <li>Coffee</li>
			<ul> <!-- Segundo ul -->
				<li>Beer</li>
				   <ul> <!-- Tercer ul -->
					<li>Coffee</li>
					<li>Tea</li>
					<li>Milk</li>
				  </ul>
				<li>Cola</li>
				<li>Water</li>
			</ul>	
		  <li>Juice</li>
		  <li>Wine</li>
	</ul>
    
asked by Roarca 13.05.2018 в 16:32
source

1 answer

1

If you are able to get event.target.type it is because you already have access to the object that received the event (in this case event.target ). Therefore you can manipulate this object doing for example event.target.innerText = "Seleccionado"; .

function cambiar(event) {
  var tag = event.srcElement ? event.srcElement.tagName : event.target.type;
  document.getElementById('seleccionado').innerText = "El elemento selecionado ha sido " + tag;
  event.target.innerHTML += "<ul><li>Agregado</li></ul>";
}
<div id="seleccionado"></div>
<ul onclick="cambiar(event)">
  <!-- Primer ul -->
  <li>Coffee</li>
  <ul>
    <!-- Segundo ul -->
    <li>Beer</li>
    <ul>
      <!-- Tercer ul -->
      <li>Coffee</li>
      <li>Tea</li>
      <li>Milk</li>
    </ul>
    <li>Cola</li>
    <li>Water</li>
  </ul>
  <li>Juice</li>
  <li>Wine</li>
</ul>
    
answered by 13.05.2018 / 17:56
source