This is just an exercise that I thought of while playing with jsFiddle.
Given elements with a data attribute:
<div data-test-id="3214581">Loading...</div> <div data-test-id="6584634">Loading...</div>
I want to set the text content to result of function with that ID, such that final DOM is:
<div data-test-id="3214581">John, Smith</div>
so far I was able to find the given element and but somehow can't refer to the element using this
keyword to get its testId:
$('div[data-test-id]').text(getPersonName($(this).data('testId')))
getPersonName() returns "John, Smith"
I think it should be that simple, but haven't found a self-referencing example like this on stack or jQuery docs.
EDIT: Fixed element to show multiple divs, not just one. (i.e. the ID is not known and shouldn't be in selector). Fixed select to have single quotes around it.
this
is the context of the function.
If nothing specifies further, this
is simply window
.
What you want is to pass a callback to $.text
, that will be bound to the selected DOM element:
$('div[data-test-id]').text(function(){
// here this is your div
return getPersonName($(this).data('testId'))
})
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments