Search code examples
phpjqueryhtmlparent

Addressing the Parent DOM in jQuery


I have a webpage that generated the same DIV according to categories in a database using a simple query. So in this case there are two categories. Each DIV has a button that when clicked should change the text of the current DIVs titleText.

<body>

<div class="DOMParent" style="width: 100%; border: 1px solid #ff0000; margin: 10px; padding:10px;">
    <div class="title">
        <div class="titleText">Category 1</div>
        <button id="btn">id="btn" Click Me</button>
    </div>
</div>

<div class="DOMParent" style="width: 100%; border: 1px solid #ff0000; margin: 10px; padding:10px;">
    <div class="title">
        <div class="titleText">Category 2</div>
        <button id="btn">id="btn" Click Me</button>
    </div>
</div>


<script>

    dp("#btn").click(function(){
        dp(".titleText").html("This is the new TITLE Text");
    });

</script>

</body>

My problem is that in Category 1 for example, if I click that button then it will change the html for both titleText when it should only change the html for the titleText in Category 1.

I have tried using incremental ids and all sorts which are definitely not the answer. So how to I change the titleText only in the Button's current DOMParent div?

This sample code is written just to simplify my problem so that the code is much smaller. I have left out the mysql query and sorts because in the end this is literally what is generated.


Solution

  • id property is unique value, so you need to change buttons id attribute to class.

    <button class="btn"> Click Me</button>
    

    and now you want to access parent, so you should use parent() method of jQuery. and then you need to find children .titleText with find method.

    So you can write code like this, and check below example fiddle

    $(this).parent().find(".titleText").text("This is the new TITLE Text");
    

    Example