Mulgard Mulgard - 5 months ago 16
jQuery Question

Use Id for multiple divs and get content using jQuery

I have a very special problem today using Spring, Thymeleaf, Html and JavaScript. I have multiple data sets coming from my Java Backend and for each dataset i have to create a

<div />
and to bind data to hidden divs:

<div class="container page-small" th:each="line: ${LINES}">
<div id="line_data_titles" hidden="true" th:attr="data-txt=${line.titles}"></div>
...
</div>


Using this it would mean that i have a
<div>
with id
line_data_titles
exactly
X
times. There is no way around that. At least nothing is getting in my mind to solve this. So to my question:

If i now use
jQuery
to get the data from my div:

<div class="container page-small" th:each="line: ${LINES}">
<div id="line_data_titles" hidden="true" th:attr="data-txt=${line.titles}"></div>
...
<script>
var titles = $("#line_data_titles").data("txt");
</script>
</div>


Is it possible to make that
JavaScript
code only valid inside the
<div>
where it is defined so that
jQuery
will only read the value from the
<div>
with the id
line_data_titles
from within the div where it is defined? I hope you understand what i mean. It would look like this:

<div class="container page-small">
<div id="line_data_titles" hidden="true" data-txt="titles of line 0"></div>
...
<script>
var titles = $("#line_data_titles").data("txt");
</script>
</div>

<div class="container page-small">
<div id="line_data_titles" hidden="true" data-txt="titles of line 1"></div>
...
<script>
var titles = $("#line_data_titles").data("txt");
</script>
</div>

<div class="container page-small">
<div id="line_data_titles" hidden="true" data-txt="titles of line 2"></div>
...
<script>
var titles = $("#line_data_titles").data("txt");
</script>
</div>

....


So i want
jQuery
to only pick the id of the div where the
JavaScript
is defined. Is that possible?

Answer

Is it possible to make that JavaScript code only valid inside the where it is defined so that jQuery will only read the value from the with the id line_data_titles from within the div where it is defined?

It's not possible, you would have to assign a different id to each element — they have to be unique. Your HTML is not valid if you have more than one element with the same id.

Similar to what "Rejith R Krishnan" said, your problem could likely be solved with dynamic ids, something along the lines of:

<div class="container page-small" th:each="line: ${LINES}">
    <div id="line_data_titles_${lines.id}" hidden="true" th:attr="data-txt=${line.titles}"></div> 
    ...
    <script>
        var titles = $("#line_data_titles_${lines.id}").data("txt");
    </script>
</div>

I hope that helps!