Behrouz Riahi Behrouz Riahi - 4 months ago 11
Node.js Question

how to retrieve an HTML attribute value in jQuery?

Is it possible to retrieve the value of an HTML in jQuery
For example if i have the following html in the front-end

<h1 id="<%= course.ownByStudent[i].user._id%>">Hello World!</h1>


I want to retrieve the value of the
id
which is
<%= course.ownByStudent[i].user._id%>
in the backend.

How do i accomplish this?

Answer

If I understand you correctly. Let's say that the server response for course.ownByStudent[i].user._id is server_id.

So you can get the h1 element using document.querySelector('h1'), then access to the id attribute as property of the h1 element.

And the result is:

var id = document.querySelector('h1').id;
alert(id);
<h1 id="server_id">Hello World!</h1>

jQuery version:

var id = $('h1')[0].id;
alert(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="server_id">Hello World!</h1>