Hello.

there is html:

<div id="arr"> <div class="test">sdvsdvsdv</div> <div class="test">4349567294</div> </div> 

you need using addEventListener, getElementById and document.getElementsByClassName without using JQUERY when clicking on <div class="test"></div> to get the html value of the item you clicked.

    2 answers 2

    This can be done for example: https://jsfiddle.net/matkdLxf/

    Same thing with getElementsByClassName: https://jsfiddle.net/23w21c3z/

     var test_items = document.querySelectorAll(".test"); var result = document.getElementById("result"); for (var i = 0; i < test_items.length; i++) { test_items[i].addEventListener("click", function () { result.innerHTML = this.innerHTML; }, false); } 
     #result { margin-top: 20px; border-top: 2px solid #ccc; padding-top: 10px; } 
     <div id="arr"> <div class="test">sdvsdvsdv</div> <div class="test">4349567294</div> </div> <div id="result"> </div> 

    • I thought it was possible without a cycle, because In jq, it is all made simple. then I will do as you showed. thanks) - ikerya
    • @ikerya, how do you think it works inside jQuery?)) - IonDen
    • @ikerya, jQuery internally uses its own function each (the same loop) to execute functions on all selected elements - Grundy
    • @IonDen $(".test").click(function(e) {}); I don't think, I know :) - ikerya
    • @ikerya, and just inside the click , each is called. Therefore, if we take out the cycle into a separate function, it will be the same. - Grundy

    If all .test elements are in #arr, then you can do without a loop: https://jsfiddle.net/cauo1755/

     var element = document.getElementById('arr'); element.addEventListener('click', function(e){ var target = e.target; // элемент по которому кликнули var value = target.innerHTML; alert(value); }, false); 
    • If inside .test is something else, then it will not roll - andreymal
    • The author did not set such a task. however, I will disprove your statement, e.target is the element that was clicked, so the level of nesting does not matter. jsfiddle.net/cauo1755/1 - Raul Rojas
    • jsfiddle.net/cauo1755/2 click on Karl - andreymal
    • Well, the fact that the author did not write such a question in the question may mean not the absence of such a task, but the fact that he simply did not consider this important and decided not to write or forgot to write, this is firstly; Secondly, those who came from Google may have such a task.) - andreymal
    • I presented a solution within the framework of the question asked by the author, why make a “motorcycle” when a “bicycle” is enough for a specific task. As for your example, when we click on the word Карл , in e.target we will get exactly the element we hit for the <div class="test"><span>Карл у</span> Клары украл кораллы</div> this approach is not designed. - Raul Rojas