Reputation: 1994
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.
Upvotes: 1
Views: 820
Reputation: 22817
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'))
})
Upvotes: 4
Reputation: 1
It is not necessary use iteration methods; .text()
iterates each element at selector , this
is already current element within function of .text(function(index, text){})
.
You can adjust getPersonName
to signature of .text()
which should allow you to use pattern
$("div[data-test-id]").text(getPersonName);
var names = {
3214581: "John, Smith",
6584634: "Stack, Overflow"
}
function getPersonName(index, text) {
return names[$(this).data().testId]
}
$("div[data-test-id]").text(getPersonName);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div data-test-id="3214581">Loading...</div>
<div data-test-id="6584634">Loading...</div>
Upvotes: 1
Reputation: 4018
I got curious as to how much longer a pure javascript translation would be compared to moonwave99's answer. Just in case someone is interested in this as well, here it is:
[].forEach.call(document.querySelectorAll("div[data-test-id]"),function(el){
el.innerHTML=getPersonName(el.getAttribute("data-test-id"));
});
Upvotes: 1
Reputation: 3909
Unfortunately the this
keyword won't help you to do this in the current context. You'll need to use jQuery's each
to loop over the results of the $(div[data-test-id])
query. Then, inside the callback given to each, the value of this
will be bound to the DOM node.
// "this" in this scope is not the DOM element
$(div[data-test-id]).each(function() {
// "this" inside this scope is bound to the DOM element
$(this).text(getPersonName($(this).data('testId')));
});
Upvotes: 2