[Solved] Get paragraph text inside specified paragraph [closed]


To get the original element that triggered the event, you should use something like this:

<div id="items" onclick="myfunction(event);">

function myfunction(e) {
    var evt = e || window.event;
    var tar = evt.target || evt.srcElement;
    // Should probably check that the tar element is a <p> and has the specific id/class
    var val = tar.innerHTML;
    alert(val);
}

http://jsfiddle.net/GtfDf/

On a similar note, unique id attributes are required in order for getElementById to work properly, and for valid HTML. Another option is to bind an event to each <p> element, and instead of using id, use class. Like this:

<div id="items">
    <p class="item">a</p>
    <p class="item">b</p>
    <p class="item">c</p>
    <p class="item">d</p>
    <p class="item">e</p>
</div>

window.onload = function () {
    var items_div = document.getElementById("items");
    var items = items_div.querySelectorAll(".item");
    for (var i = 0; i < items.length; i++) {
        items[i].onclick = myfunction;
    }
};

function myfunction() {
    var val = this.innerHTML;
    alert(val);
}

http://jsfiddle.net/eWZyn/1/

But there are many options/alternatives for using the getElementById/querySelectorAll, and may or may not be better.

The first example is “better” for dynamic items being added/removed from the div. The second example seems more appropriate, in my opinion, for static items. I only say that in case there are other elements inside the div that could be handled for the click event. Either way, I hope these example help.

2

solved Get paragraph text inside specified paragraph [closed]