0

I am working on below jQuery code and target is to change content of any tag is clicked by the user.

I am fine with getting the id of clicked element but not able change its content.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>   
<script>
    $(document).ready(function(){
        $("td").click(function(){
            var elementID = $(this).attr('id');
            alert(elementID); //I am OK by accessing the elementID
            $("#elementID").text("X"); // How pass this elementId again in order to change content ?
        });
    });
</script>
1
  • 3
    $(this), just like you did in the first row of the function... Commented Mar 20, 2018 at 13:20

3 Answers 3

4

You already have the element by accessing $(this).

$(document).ready(function(){
    $("td").click(function(){
        $(this).text("X");
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, need to have more understanding about basics :))
-1

correct your line with this: $("#"+elementID).text("X");

1 Comment

Correct it to what?
-2
$("td").click(function(){
   var elementID = $(this).attr('SomeOtherElementID');
   $("#" + elementID).text("X");
});

3 Comments

I think it is a better way to do it directly with $(this).text('X')
I think that by doing this he doesn't want to change $(this) element. Probably, he would like just to get SomeOtherElementID and change it's content.
in your case SomeOtherElementID isnt some-other-element -> You try to access an attribute on the clicked element. So in your example the <td> tag need a <td SomeOtherElementID="otherElementId"> and I don't think that this would help @crowley

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.